如何从两个pandas数据帧加入单元格值?

时间:2017-03-12 19:48:29

标签: python pandas dataframe merge concatenation

如何从两个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

如何将这些数据框内的值(具有相同的columnrow索引)与逗号组合在一起?

预期输出如:

         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.

谢谢,

2 个答案:

答案 0 :(得分:3)

您可以使用concat DataFramesstring groupbyindex join df = pd.concat([df1,df2]).astype(str).groupby(level=0).agg(','.join) df.index.name = df1.index.name print (df) 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 聚合astype } function WindowState="Maximized" WindowStyle="None"

npm install -g phonegap

答案 1 :(得分:2)

你可以用" string"将它们总结为两个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