Skip to main content
 首页 » 编程设计

python之如何加入两个 Pandas 数据框中的单元格值

2025年05月04日23三少

如何加入两个 pandas 数据框中的单元格值?

df1 is: 
 
         F1   F2   M1   M2 
    pos 
    23  1.0  0.0  1.0  1.0 
    24  1.0  1.0  1.5  1.0 
    28  1.0  0.0  0.5  0.0 
 
 
df2 is: 
 
         F1   F2   M1   M2 
    pos 
    23  0.0  1.0  0.5  0.0 
    24  1.0  1.0  1.5  1.0 
    28  0.0  1.0  1.0  1.0 

如何将这些数据框中的值(具有相同的 column 和 row 索引)用逗号组合起来?

预期输出如下:

         F1       F2       M1       M2 
    pos 
    23  1.0,0.0  0.0,1.0  1.0,0.5  1.0,0.0 
    24  1.0,1.0  1.0,1.0  1.5,1.5  1.0,1.0 
same for other lines... 
The value of df1 should be place before comma and df2 after that. 

谢谢,

请您参考如下方法:

您可以将它们总结为两个具有“字符串”元素的 DF:

In [324]: d1.astype(str).add(',').add(d2.astype(str)) 
Out[324]: 
          F1       F2       M1       M2 
pos 
23   1.0,0.0  0.0,1.0  1.0,0.5  1.0,0.0 
24   1.0,1.0  1.0,1.0  1.5,1.5  1.0,1.0 
28   1.0,0.0  0.0,1.0  0.5,1.0  0.0,1.0