gpt4 book ai didi

python - 合并具有两个公共(public)值的行 | Python

转载 作者:行者123 更新时间:2023-12-05 09:09:01 24 4
gpt4 key购买 nike

我一直在为看起来简单的行间合并而苦苦挣扎。我有两个具有以下列值的 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

关于python - 合并具有两个公共(public)值的行 | Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62765465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com