首页 > 解决方案 > Pandas - 将多行从另一个 DF 映射到多列

问题描述

我有两个数据框,我正在尝试将数据从一个迁移df1到我的 main df

它们共享一个公共键 - 我想将一行中的值存储df1到一df列中。我可以这样做..但是 df1可以有多行(最多 5 行)共享公共键,我想将每一行存储在一个单独的列中。

使用示例:

df

index  key   datacol 
  1    1AA    data1 
  2    1AB    data2
  3    1AC    data3

df1

index  key   newdata 
  1    1AA    new1
  2    1AB    new2
  3    1AB    new3
  4    1AB    new4 
  5    1AC    new5
  6    1AC    new6

输出:

index  key   datacol newcol1 newcol2 newcol3
  1    1AA    data1   new1
  2    1AB    data2   new2    new3    new4
  3    1AC    data3   new5    new6

感谢您的帮助。

标签: pythonpandasdataframe

解决方案


IIUC,可以

d = df2.groupby('key', as_index=False).agg(list)
x = pd.concat([d.newdata.apply(pd.Series), d.key],1).set_index('key')
pd.merge(df.set_index('key'),x, right_index=True, left_index=True)

        index   datacol  0      1       2
key                 
1AA      1      data1    new1   NaN     NaN
1AB      2      data2    new2   new3    new4
1AC      3      data3    new5   new6    NaN

推荐阅读