我一直在为看起来简单的行间合并而苦苦挣扎。我有两个具有以下列值的 pandas DataFrame
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”的值,但它合并它们的方式就好像我刚刚删除了其中一行或者根本没有值(value)。如何获得所需的输出?
最佳答案
您可以利用 groupby 的 first/last 功能。
在这种情况下:
df.groupby(['food']).last().reset_index()
输出
1 0 2 3 4 5 6
0 apple 1 red fruit round soft 2020-06-05
1 cheese 2 yellow dairy squared soft 2020-06-07
2 lemon 3 green fruit round NaN NaT
https://stackoverflow.com/questions/62765465/
相关文章:
android - CameraX - 在纵向模式下锁定 Activity 时仅旋转预览
javascript - 如何使用 react 模态显示没有背景效果的模态?
ios - Flutter NSException : Configuration fails. 可
amazon-web-services - terraform 可以复制 s3 存储桶的内容吗?
javascript - 如何使用 typescript 导出 Mongoose 模式?
r - 使用 R Shiny 中的操作按钮将行从一个 DT 移动到其他 DT
php - 试图从 laravel 中 Eloquent 产品评论中获取评论者的姓名