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']
CodePudding user response:
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
CodePudding user response:
def code(x = 'x are values in the columns'):
'''It will look for 3rd key in the code and fit 'ZZZ' in that place if there is no value in that'''
y = x.split('_')[2]
z = x.split('_')[3]
a = x.split('_')[:2]
if y =='':
y = y.replace('', 'ZZZ')
return '_'.join(a [y] [z])
else:
return x
Df['A'].apply(code)