代码之家  ›  专栏  ›  技术社区  ›  swifty

pandas-将多行从另一个df映射到多列

  •  1
  • swifty  · 技术社区  · 6 年前

    我有两个数据帧,我正在尝试从一个数据帧迁移数据 df1 我的主要 df .

    它们共享一个公共密钥-我希望存储 DF1 排成一行 东风 列。我能做的…… 然而 DF1 可以有多行(最多5行)共享公共键和 我想将每一行存储在一个单独的列中。

    举个例子:

    东风

    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
    

    感谢你的帮助。

    2 回复  |  直到 6 年前
        1
  •  1
  •   rafaelc    6 年前

    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
    
        2
  •  0
  •   rafaelc    6 年前

    你可以先合并

    newdf=df.merge(df1,how='right')
    

    然后使用 cumcount 创建帮助键,然后问题看起来像 pivot

    finaldf= newdf.assign(helpkey=newdf.groupby('key').cumcount()).set_index(['key','datacol','helpkey']).newdata.unstack(fill_value='')
    finaldf
    Out[410]: 
    helpkey         0     1     2
    key datacol                  
    1AA data1    new1            
    1AB data2    new2  new3  new4
    1AC data3    new5  new6