基于第一列中的字符串跨数据帧聚合数据

2024-05-08 17:21:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,将多个数据帧中的信息聚合到一个新数据帧中最经济的方法是基于匹配一个ID

每个df都有一个“participant\u id”列,每行都有一个不同的participant id。我想最后得到一个df,其中有一个participant\u id列,其他列中每个df的得分。你知道吗

所以我必须需要一个变量来保存参与者ID,循环遍历每一行并提升必要的列。然后,需要将所有相应的分数放在相应的行上,并与正确的参与者ID相关联

我不确定这是否是解决问题的最佳方法?什么时候匹配参与者ID才有意义?早还是晚?你知道吗

输入数据和预期输出:

### three datasets 

d1 = {'part_id': ['PartID_1234', 'PartID_5678'], 'col2': [1, 2]}
df1 = pd.DataFrame(data=d1)

d2 = {'part_id': ['PartID_1234', 'PartID_5678'], 'col2': [3, 4]}
df2 = pd.DataFrame(data=d2)

d3 = {'part_id': ['PartID_5678', 'PartID_1234'], 'col2': [5, 6]}
df3 = pd.DataFrame(data=d3)


### aggregated dataset based on ID

import numpy as np

result = pd.DataFrame(np.array([['PartID_1234', 1, 3, 6], ['PartID_5678', 2, 4, 5]]))

Tags: 数据方法iddataframedfdata参与者col2
2条回答

我相信您需要^{}^{}来表示每个DataFrame,以便在列表理解中按列part_id进行索引:

dfs = [df1, df2, df3]
dfs = [x.set_index('part_id')['col2'] for x in dfs]
df = pd.concat(dfs, axis=1).reset_index()
df.columns = range(len(df.columns))
print (df)

             0  1  2  3
0  PartID_1234  1  3  6
1  PartID_5678  2  4  5

如果需要索引中的第一列:

dfs = [df1, df2, df3]
dfs = [x.set_index('part_id')['col2'] for x in dfs]
df = pd.concat(dfs, axis=1, ignore_index=True)
print (df)

             0  1  2
PartID_1234  1  3  6
PartID_5678  2  4  5

可以将mergehow='outer'一起使用,以获得预期的外部联接效果,如:

df1.merge(df2, on='part_id', how='outer').merge(df3, on='part_id', how='outer')

    part_id     col2_x  col2_y  col2
0   PartID_1234   1        3    6
1   PartID_5678   2        4    5

相关问题 更多 >