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

标签 python pandas dataframe

我有两个数据框,即 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 

类似地,对于所有其他人。

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

最佳答案

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

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

关于python - 根据列值将数据从一个 pandas 数据框复制到另一个,并用逗号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953875/

相关文章:

python - 在 python pandas 数据帧中添加时间序列强度的廉价方法

Python - 根据列的最大值删除重复项

r - 如何操作(聚合)R 中的数据?

Python 读取修饰键(CTRL、ALT、SHIFT)

python - 在 Pandas 中生成给定范围内的随机日期

python - 选择排序的重复问题

python - 数据帧中的.map(str) 和.astype(str) 有什么区别

python - Pyspark:选择除特定列之外的所有列

python - 按类型全选 : Geometry. 等效的 Python 脚本?

Python - 如何在没有 MemoryError 的情况下 gzip 大文本文件?