【问题标题】:Copying data from one pandas dataframe to other based on column value and separated by comma根据列值将数据从一个熊猫数据帧复制到另一个数据帧并用逗号分隔
【发布时间】:2018-02-24 04:01:45
【问题描述】:

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

同样,对于所有其他人。

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

【问题讨论】:

  • 请检查更新

标签: python pandas dataframe


【解决方案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

【讨论】:

  • 我得到这个 TypeError: ('sequence item 3: expected str instance, float found', 'occured at index P1')
  • 我只是忘了在原来的问题中提到 NAN,并为提出类似的问题而道歉。我觉得这有点不同,并且有完全形成不同问题的权重
  • @Rookie_123 不用担心,我也很难找到不同的。
  • 有什么办法可以删除那些出现在 Sf,Bd 下方的 Z3 列中的 ,,
  • @Rookie_123 yw :-) 祝你有美好的一天
猜你喜欢
  • 2022-01-24
  • 2022-10-23
  • 2021-03-02
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多