【问题标题】:Combining two dataframe rows into one将两个数据框行合并为一个
【发布时间】:2020-06-16 21:52:26
【问题描述】:

我有一个数据框 df,有 3 列:namesalaryposition

我正在尝试创建一个新的数据框,其中包含任意两行的所有可能组合,我已部分使用:

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),其中包含六列 name1name2salary1salary2position1position2。每列将包含各自行的数据 - 例如,name1 将包含 name 中的值,用于合并的两行中的第一行,name2 将包含 name 中的值,用于第二行两行。

目前,代码生成三列(namesalaryposition),将原始数据帧中的字符串连接在一起。例如,第一行的name 值为“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})

【问题讨论】:

  • 你能发布你的数据吗
  • 数据已添加
  • 您还可以添加一些预期的输出吗?如果我没记错的话,你想要 df2['name1'][0]="Barnes Daviesdf2['name2'][0]="Davies 吗?薪水和职位会发生什么?列的长度可能不相等,其余值是否使用None
  • 第 1 行的预期输出为:name1="Barnes" name2="Davies" Salary1=51 Salary2=48 position1='0' position2='1'
  • 您的数据有奇数个值。在最后一行的情况下,name2、salary2 和 position2 会发生什么?他们没有吗?或者你第二行有 name1 作为 Davies 吗?

标签: python pandas combinations


【解决方案1】:
import pandas as pd
from itertools import combinations
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']

df=pd.DataFrame({'name':name,'salary':salary,'position':position})
cc=list(combinations(df.index,2))
## create empty df2
df2=pd.DataFrame(columns=['name1','name2','salary1','salary2','position1','position2'])
## generate rows by combination in cc
for ind,i in enumerate(cc):
    l1=df.loc[i[0]]
    l2=df.loc[i[1]]
    temp=[l1['name'],l2['name'],l1['salary'],l2['salary'],l1['position'],l2['position']]
    df2.loc[ind] = temp

print(df2)

给出一个类似这样的数据框(间距因从 jupyter notebook 复制而失真):

    name1   name2   salary1 salary2 position1   position2
0   Barnes  Davies  51      48      0           1
1   Barnes  Fernandes   51  52      0           1
2   Barnes  Freeman 51      69      0           1
3   Barnes  Gomes   51      46      0           1
4   Barnes  Gray    51      83      0           2
... ... ... ... ... ... ...
100 McCarthy    Ward    48  49      0           1
101 McCarthy    Smith   48  62      0           3
102 Pereira Ward    65      49      3           1
103 Pereira Smith   65      62      3           3
104 Ward    Smith   49      62      1           3

【讨论】:

  • 哇。一个简单而有效的答案,让我难倒了几个小时。谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多