我有2个数据帧df1
ID df1_Members
100 Eric
200 Chris
300 Jordan
400 Samantha
600 Audrey
df2
ID df2_Members
100 Eric
200 Chris
300 Jordan
400 NaN
500 NaN
我正在合并数据框`
df_merge=pd.merge(df1,df2,on='ID',how='left')
和合并的数据框看起来像这样
ID df1_Members df2_Members
100 Eric Eric
200 Chris Chris
300 Jordan Jordan
400 Samantha NaN
600 Audrey NaN
由于ID 600不在df2中,我想用“无数据”替换对应于ID 400的NaN,用“ ID不存在”替换对应于ID 600的ID
我正在尝试这样做,但是没有用
if (df_merge['df2_Members']==np.nan) & (df1['ID'].isin(df2['ID'])):
df_merge['df2_Members'].fillna('No Data',inplace=True)
#ID in df1 doesn't exist in df2
elif (df_merge['df2_Members']==np.nan) &(~df1['ID'].isin(df2['ID'])):
df_merge['df2_Members']="ID doesn't exist in df2"
`
答案 0 :(得分:0)
尝试一下:
df_merge.loc[(df_merge['df2_Members'].isna()) & (df_merge['ID'].isin(df2['ID'])), 'df2_Members'] = 'No Data'
df_merge.loc[(df_merge['df2_Members'].isna()) & (~df_merge['ID'].isin(df2['ID'])), 'df2_Members'] = "ID doesn't exist in df2"
df_merge
应该返回您想要的东西
ID df1_Members df2_Members
0 100 Eric Eric
1 200 Chris Chris
2 300 Jordan Jordan
3 400 Samantha No Data
4 500 Audrey No Data
5 600 Johnny ID doesn't exist in df2
我添加了ID 600作为df2中不存在的另一个名称