基于唯一行的 Concat python 数据帧

cur*_*guy 6 python pandas pandas-groupby

我的数据框读起来像:

df1

user_id    username firstname lastname 
 123         abc      abc       abc
 456         def      def       def 
 789         ghi      ghi       ghi
Run Code Online (Sandbox Code Playgroud)

df2

user_id     username  firstname lastname
 111         xyz       xyz       xyz
 456         def       def       def
 234         mnp       mnp        mnp
Run Code Online (Sandbox Code Playgroud)

现在我想要一个像

 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
Run Code Online (Sandbox Code Playgroud)

由于 user_id456在两个数据帧中都是通用的。我已经在 user_id 上尝试过 groupby groupby(['user_id'])。但看起来 groupby 需要跟随一些aggregation我不想要的东西。

jez*_*ael 5

使用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
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)

编辑:

使用boolean indexing和的另一种解决方案numpy.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
Run Code Online (Sandbox Code Playgroud)