我将2个CSV文件与pandas python进行比较,一切正常。它匹配 employee_id 列并将结果输出到csv文件
df1 = pd.read_csv('input1.csv', sep=',\s+', delimiter=',', encoding="utf-8")
df2 = pd.read_csv('input2.csv', sep=',\s,', delimiter=',', encoding="utf-8")
df3 = pd.merge(df1,df2, on='employee_id', how='right')
df3.to_csv('output.csv', encoding='utf-8', index=False)
如果找不到匹配项,则会返回空白结果,我希望它返回 not_found
Pandas可以这样做,或者之后我应该做一些处理吗?
答案 0 :(得分:2)
我认为如果NaN
中没有df1
,您可以使用fillna
:
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
或{{3}通过~
否定掩码:
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