Python 将两个数据帧行合并为一行

Python 将两个数据帧行合并为一行,python,pandas,combinations,Python,Pandas,Combinations,我有一个数据框,df,有三列:name、salary和position 我正在尝试创建一个新的数据帧,其中包含任意两行的所有可能组合,我已经使用以下方法部分实现了这一点: from itertools import combinations import pandas as pd cc = list(combinations(df.index,2) df2 = pd.DataFrame([df.loc[c,['name','salary','position']] for c in cc],

我有一个数据框,
df
,有三列:
name
salary
position

我正在尝试创建一个新的数据帧,其中包含任意两行的所有可能组合,我已经使用以下方法部分实现了这一点:

from itertools import combinations
import pandas as pd

cc = list(combinations(df.index,2)
df2 = pd.DataFrame([df.loc[c,['name','salary','position']] for c in cc], index=cc)
我希望此代码创建一个新的数据框(
df2
),其中包含六列
name1
name2
salary1
salary2
position1
,和
position2
。每列将包含各自行的数据-例如,
name1
将包含组合的两行中第一行的
name
中的值,而
name2
将包含两行中第二行的
name
中的值

目前,代码生成三列(
name
salary
position
),将原始数据帧中的字符串连接在一起。例如,第一行的
名称
值是'JohnSmithJaneDoe'。由于所有条目的长度不同,我不能简单地将它们分为两列

编辑:

我的数据是:

name = ['Barnes', 'Davies', 'Fernandes', 'Freeman', 'Gomes', 'Gray', 'Henderson', 'James', 'Jota', 'Kelly', 'Long', 'McCarthy', 'Pereira', 'Ward', 'Smith']
salary = [51, 48, 52, 69, 46, 83, 123, 78, 71, 63, 61, 48, 65, 49, 62]
position = ['0', '1', '1', '1', '1', '2', '2', '2', '2', '2', '3', '0', '3', '1', '3']

pd.DataFrame({'name':name,'salary':salary,'position':position})
将熊猫作为pd导入
从itertools导入组合
name=[“巴恩斯”、“戴维斯”、“费尔南德斯”、“弗里曼”、“戈麦斯”、“格雷”、“亨德森”、“詹姆斯”、“约塔”、“凯利”、“朗”、“麦卡锡”、“佩雷拉”、“沃德”、“史密斯”]
薪水=[51,48,52,69,46,83,123,78,71,63,61,48,65,49,62]
位置=['0','1','1','1','2','2','2','2','3','0','3','1','3']
数据帧({'name':name,'salary':salary,'position':position})
cc=列表(组合(测向索引,2))
##创建空的df2
df2=pd.DataFrame(列=['name1'、'name2'、'salary1'、'salary2'、'position1'、'position2'])
##在cc中通过组合生成行
对于ind,枚举中的i(cc):
l1=df.loc[i[0]]
l2=df.loc[i[1]]
临时工=[l1['name']、l2['name']、l1['salary']、l2['salary']、l1['position']、l2['position']]
df2.loc[ind]=温度
打印(df2)
给出如下数据帧(由于从jupyter笔记本复制而导致间距扭曲):

name1 name2薪水1薪水2职位1职位2
0巴恩斯戴维斯51 48 0 1
1巴恩斯·费尔南德斯515201
2巴恩斯·弗里曼51 69 0 1
3巴恩斯戈麦斯51 46 0 1
4巴恩斯格雷51 83 0 2
... ... ... ... ... ... ...
麦卡锡病房100号48 49 01
101麦卡锡史密斯48 62 0 3
102佩雷拉病房65 49 3 1
103佩雷拉·史密斯65 62 3
104沃德史密斯49 62 1 3

您可以发布您的数据吗?数据已经添加,您还可以添加一些预期的输出。如果我没说错的话,您希望
df2['name1'][0]=“Barnes Davies
df2['name2'][0]=“Davies
?工资和职位会发生什么变化?列的长度可能不相等,是否对其余值使用
None
?第1行的预期输出为:name1=“Barnes”name2=“Davies”salary1=51 salary2=48 position1='0'position2='1'您的数据有奇数个值。如果是最后一行,姓名2、薪水2和职位2会发生什么变化?没有吗?或者你第二排的名字是戴维斯吗?哇。一个简单而有效的答案让我困惑了好几个小时。非常感谢。