首页 文章

根据列值将数据从一个pandas数据帧复制到另一个pandas数据帧,并用逗号分隔

提问于
浏览
2

我有两个数据帧,即df1和df2 .

df1 就像

Index YH   HE  MT  CU  EI
 0    Dot  Sf  Sy  Lc  
 1    Rls  Bd  Sa  Ta  
 2    Fs       Ft  Rg

df2 就像

Index   Z1   Z2  Z3
 0      YH       HE
 1      HE       EI
 2      MT       CU

我想要一个 df3 ,看起来像这样

Index   Z1           Z2     Z3
 0      YH                  HE
 1      HE                  EI
 2      MT                  CU  
 3      Dot,Rls,Fs          Sf,Bd
 4      Sf,Bd              
 5      Sy,Sa,Ft            Lc,Ta,Rg

基本上,只在一个单元格中,但用逗号分隔 . 逗号分隔的单元格从df1获得 .

在df3中,行3,4,5对应于行0,1,2

(0,Z1) of df2 is YH and column YH in df1 is Dot,Rls,Fs 
So Dot,Rls,Fs comes at (3,Z1) in df3

(1,Z1) of df2 is HE and HE column has Sf,BD in df1 
So Sf,Bd comes at (4,Z1) in df3

同样,对所有其他人 .

如果还不清楚,请告诉我 .

1 回答

  • 1

    答案已包含在上一个问题中

    s=df2.set_index('Index').astype(object).apply(lambda x : x.map(df1.set_index('Index').to_dict('l')))
    
    
    pd.concat([df2.set_index('Index'),s.fillna('').applymap(','.join)])
    
    Out[1798]: 
                   Z1 Z2        Z3
    Index                         
    0              YH           HE
    1              HE           EI
    2              MT           CU
    0      Dot,Rls,Fs       Sf,Bd,
    1          Sf,Bd,           ,,
    2        Sy,Sa,Ft     Lc,Ta,Rg
    

    更新

    s=df2.set_index('Index').astype(object).apply(lambda x : x.map(df1.set_index('Index').replace('',np.nan).stack().groupby(level=1).apply(list).to_dict()))
    pd.concat([df2.set_index('Index'),s.fillna('').applymap(','.join)])
    Out[1815]: 
                   Z1 Z2        Z3
    Index                         
    0              YH           HE
    1              HE           EI
    2              MT           CU
    0      Dot,Rls,Fs        Sf,Bd
    1           Sf,Bd             
    2        Sy,Sa,Ft     Lc,Ta,Rg
    

相关问题