Python 如何将两个数据帧中的单元格值连接起来?
如何将两个数据帧中的单元格值连接起来Python 如何将两个数据帧中的单元格值连接起来?,python,pandas,dataframe,merge,concatenation,Python,Pandas,Dataframe,Merge,Concatenation,如何将两个数据帧中的单元格值连接起来 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
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
如何用逗号组合这些数据帧中的值(具有相同的列
和行
索引)
预期输出,如:
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.
谢谢,您可以将数据帧
、转换为字符串
和groupby
通过索引
与聚合函数连接
:
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
您可以将DataFrames
、cast tostring
by和groupby
byindex
与aggregate by函数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
您可以将它们汇总为两个带有“字符串”元素的DFs:
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
您可以将它们汇总为两个带有“字符串”元素的DFs:
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
pos索引丢失。事实上,还有很多其他的索引。我更喜欢这个答案,因为我认为它在你想要的细胞连接方式上更一般。例如,我希望将我的单元格组合为一个元组,因此我只替换了
,”。在agg
方法中用tuple
连接。pos索引丢失。事实上,还有很多其他的索引。我更喜欢这个答案,因为我认为它在你想要的细胞连接方式上更一般。例如,我希望我的单元格组合为一个元组,所以我只替换了,”。在agg
方法中用tuple
连接。谢谢,但是pos
索引值呢?我有多个列被设置为索引,并希望保留它们。@everestial007,这应该也适用于多索引DFS,事实上确实如此。谢谢。@MaxU-我喜欢你的解决方案+1谢谢,但是pos
索引值呢?我有多个列被设置为索引,并希望保留它们。@everestial007,这应该也适用于多索引DFS,事实上确实如此。谢谢。@MaxU-我喜欢你的解决方案+1