I've got two panas dataframe, and I would like to generate one more with them:
import pandas as pd
df_name=pd.DataFrame({'CODE':['01','02','03','04'],
'NAME':['MICK','DAVID','JEAN','CHERRY']})
df_exp=pd.DataFrame({'TEST':['POST1','POST2','POST3','POST4','POST5','POST6','POST7', 'POST8'],
'PERS CODE':['02','','','04','','02','','03'],
'PERS2 CODE':['03','01','02','01','04','02','01','05']})
print(df_name)
print(df_exp)
df_output=pd.DataFrame()
df_output['POST']=df_exp['TEST']
df_output['AGENT'] = df_exp['PERS CODE'].map(df_name.set_index('CODE')['NAME'])
print(df_output)
but I would like a condition: if the value is empty in 'PERS CODE' it take the Value of 'PERS2 CODE'
I
CodePudding user response:
You can use mask
to fill the empty 'PERS CODE'
entries with those of 'PERS2 CODE'
:
df_output['AGENT'] = df_exp['PERS CODE'].mask(df_exp['PERS CODE'].eq(''), df_exp['PERS2 CODE']).map(df_name.set_index('CODE')['NAME'])