【发布时间】:2020-10-27 03:11:19
【问题描述】:
我一直在努力解决行间的简单合并问题。我有两个带有以下列值的熊猫数据框
df_a.columns.to_list()
['id','food','color','type','shape']
df_b.columns.to_list()
['id','food','smell','date']
我想看看两个 DataFrame 中是否有重复的食物以将它们合并到一个中
df_total = pd.concat([df_a, df_b], keys=['A', 'B'], ignore_index=False)
df_total = df_total.sort_values(by=['food'],ascending=True);
df_total['food'].value_counts().loc[lambda x : x>=2]
Out[1]
apple 2
cheese 2
据此,“APPLE”和“CHEESE”是重复的。打印连接表时,我们得到
id food color type shape smell date
-----------------------------------------------------------------
1 apple red fruit round NaN NaT
1 apple NaN NaN NaN soft 2020-06-05
2 cheese yellow dairy squared NaN NaT
2 cheese NaN NaN NaN soft 2020-06-07
3 lemon green fruit round NaN NaT
期望的输出:
id food color type shape smell date
-----------------------------------------------------------------
1 apple red fruit round soft 2020-06-05
2 cheese yellow dairy squared soft 2020-06-07
3 lemon green fruit round NaN NaT
我的尝试:
这次使用 pd.merge 在两个 DataFrame 中使用 .reset_index 重新定义 df_total。
df_total = pd.merge(df_a.reset_index(),df_b.reset_index(), how = 'right/left/outer/inner')
如何我使用了“right”、“left”、“outer”、“inner”的值,但它以这样的方式合并它们,就好像我刚刚删除了其中一行一样或者根本没有价值。如何获得所需的输出?
【问题讨论】:
-
请添加更多数据,因为您提供的数据似乎无法生成所需的输出。
-
@CeliusStingher 有更多数据,大约有 60 行。只是显示了一些行以使其简单。所有重复的行都遵循相同的模式,一行有“颜色”、“类型”和“形状”,但缺少“气味”和“日期”,另一行反之亦然。
-
明白了,也许我的回答可以帮助你解决问题