gpt4 book ai didi

python - 基于唯一行的 Concat python 数据帧

转载 作者:行者123 更新时间:2023-11-28 18:22:21 25 4
gpt4 key购买 nike

我的数据框是这样的:

df1

user_id    username firstname lastname 
123 abc abc abc
456 def def def
789 ghi ghi ghi

df2

user_id     username  firstname lastname
111 xyz xyz xyz
456 def def def
234 mnp mnp mnp

现在我想要一个像

这样的输出数据框
 user_id    username firstname lastname 
123 abc abc abc
456 def def def
789 ghi ghi ghi
111 xyz xyz xyz
234 mnp mnp mnp

因为 user_id 456 在两个数据帧中都很常见。我已经在 user_id groupby(['user_id']) 上尝试了 groupby。但是看起来 groupby 后面需要跟一些我不想要的 aggregation

最佳答案

使用 concat + drop_duplicates :

df = pd.concat([df1, df2]).drop_duplicates('user_id').reset_index(drop=True)
print (df)
user_id username firstname lastname
0 123 abc abc abc
1 456 def def def
2 789 ghi ghi ghi
3 111 xyz xyz xyz
4 234 mnp mnp mnp

使用 groupby 和聚合 first 的解决方案较慢:

df = pd.concat([df1, df2]).groupby('user_id', as_index=False, sort=False).first()
print (df)
user_id username firstname lastname
0 123 abc abc abc
1 456 def def def
2 789 ghi ghi ghi
3 111 xyz xyz xyz
4 234 mnp mnp mnp

编辑:

boolean indexingnumpy.in1d 的另一种解决方案:

df = pd.concat([df1, df2[~np.in1d(df2['user_id'], df1['user_id'])]], ignore_index=True)
print (df)
user_id username firstname lastname
0 123 abc abc abc
1 456 def def def
2 789 ghi ghi ghi
3 111 xyz xyz xyz
4 234 mnp mnp mnp

关于python - 基于唯一行的 Concat python 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44236940/

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