Python 合并两个数据帧时,两个数据帧上的键列均未获得完整的OuterJoin
我有两个数据帧,如下所示。我用熊猫和numpy来比较差异Python 合并两个数据帧时,两个数据帧上的键列均未获得完整的OuterJoin,python,pandas,dataframe,outer-join,Python,Pandas,Dataframe,Outer Join,我有两个数据帧,如下所示。我用熊猫和numpy来比较差异 df_a Key Value 0 data_owner John 1 locationcode local 2 Unit sales 3 appli
df_a
Key Value
0 data_owner John
1 locationcode local
2 Unit sales
3 application autosales
df_b
Key Value
0 data_owner John
1 locationcode local
2 Unit sales
3 application autosales
4 department frontoffice
我正在使用下面的代码进行合并
df = pd.merge(df_a,df_b,on=['Key'],how='outer',left_index=True,right_index=True)
df['diff'] = np.where((df['Value_x']==df['Value_y']), 'No', 'Yes')
我的输出意图是比较df和两侧的任何缺失项
下面的实际输出:但问题是我想显示两个数据帧中的键,但若你们看到下面的输出,它只显示一次,也就是说,我需要键y也是输出的一部分
Key Value_x Value_y diff
0 data_owner John John No
1 locationcode local local No
2 unit sales sales No
3 application autosales autosales No
4 department frontoffice NaN No
预期输出:我希望显示来自两个位置的键
Key_x Value_x Key_y Value_y diff
0 data_owner John data_owner John No
1 locationcode local locationcode local No
2 unit sales unit sales No
3 application autosales application autosales No
4 department frontoffice NaN NaN Yes
使用,在合并两个数据帧之前将后缀添加到两个数据帧的列中,这样它们的键在合并后不会合并到单个列中:
df = pd.merge(
df_b.add_suffix('_x'), df_a.add_suffix('_y'),
left_on='Key_x', right_on='Key_y', how='outer')
df['diff'] = np.where(df['Value_x'].eq(df['Value_y']), 'No', 'Yes')
它很有魅力。非常感谢。还有一个疑问是如何获得“不适用”而不是Nan。只需使用
df=df.fillna('notapplicative')
。
# print(df)
Key_x Value_x Key_y Value_y diff
0 data_owner John data_owner John No
1 locationcode local locationcode local No
2 Unit sales Unit sales No
3 application autosales application autosales No
4 department frontoffice NaN NaN Yes