我認爲你可以使用fillna
如果沒有NaN
在df1
:
df1 = pd.DataFrame({'employee_id':[1,2,3],
'B':[4,5,6],
'C':[7,8,9]})
print (df1)
B C employee_id
0 4 7 1
1 5 8 2
2 6 9 3
df2 = pd.DataFrame({'employee_id':[1,4,6],
'D':[4,5,6],
'E':[7,8,9]})
print (df2)
D E employee_id
0 4 7 1
1 5 8 4
2 6 9 6
df3 = pd.merge(df1,df2, on='employee_id', how='right')
df3[df1.columns] = df3[df1.columns].fillna('not_found')
print (df3)
B C employee_id D E
0 4 7 1 4 7
1 not_found not_found 4 5 8
2 not_found not_found 6 6 9
但如果NaN
在df1
需要創造面具從right
標識缺失值加入 - 在merge
與參數indicator=True
或isin
和否定面膜通過~
:
df1 = pd.DataFrame({'employee_id':[1,2,3],
'B':[np.nan,5,6],
'C':[7,8,9]})
print (df1)
B C employee_id
0 NaN 7 1
1 5.0 8 2
2 6.0 9 3
df3 = pd.merge(df1,df2, on='employee_id', how='right', indicator=True)
mask = df3['_merge'] == 'right_only'
df3.loc[mask, df1.columns.difference(['employee_id'])] =
df3.loc[mask,df1.columns.difference(['employee_id'])].fillna('not_found')
df3 = df3.drop('_merge', axis=1)
print (df3)
B C employee_id D E
0 NaN 7 1 4 7
1 not_found not_found 4 5 8
2 not_found not_found 6 6 9
df3 = pd.merge(df1,df2, on='employee_id', how='right')
mask = ~df2['employee_id'].isin(df1['employee_id'])
df3.loc[mask, df1.columns.difference(['employee_id'])] = \
df3.loc[mask,df1.columns.difference(['employee_id'])].fillna('not_found')
print (df3)
B C employee_id D E
0 NaN 7 1 4 7
1 not_found not_found 4 5 8
2 not_found not_found 6 6 9
非常感謝你,他們是很好的例子。保存我不得不處理文件後 – fightstarr20
很高興能幫助你;)美好的一天! – jezrael