如何从两个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.
谢谢,
答案 0 :(得分:3)
您可以使用concat
DataFrames
,string
groupby
和index
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