dataframe
import pandas as pd
d = {'A': ['B_502_ZZZ_01', 'B_400__01']}
df = pd.DataFrame(data=d)
I tried
def f(x):
x = x.split('_')[2]
if x=='':
x = x.replace('', 'ZZZ')
return x
else:
return x
df['A'].apply(f)
output required full value like not only 2nd position. I can split 3rd position in another column but I want position changes at that location directly.
['B_502_ZZZ_01', 'B_400_ZZZ_01']
>Solution :
You can use a regex:
df['A'] = df['A'].str.replace(r'((?:[^_]+_){2})(?=_)', r'\1ZZZ', regex=True)
NB. The 2 in the regex indicates the number of _ after which to perform the replacement
output (as new column A2 for clarity):
A A2
0 B_502_ZZZ_01 B_502_ZZZ_01
1 B_400__01 B_400_ZZZ_01