gpt4 book ai didi

python - 如何聚合扩展值 - python - pandas

转载 作者:行者123 更新时间:2023-12-01 01:43:53 24 4
gpt4 key购买 nike

我有这样的输入:

     column1     column2
MGI:97874 MP:0008796
MGI:97874 MP:0009395
MGI:97874 MP:0009937
MGI:97874 MP:0011098
MGI:97874 MP:0011703
MGI:96522 MP:0001614
MGI:96522 MP:0000364
MGI:96522 MP:0006093

我的问题是如何将相同值的行(在第一列中)合并到一行中,因此输出将如下所示:

MGI:97874 MP:0008796 MP:0009395 MP:0009937 MP:0011098 MP:0011703
MGI:96522 MP:0001614 MP:0000364 MP:0006093

最佳答案

您需要:

g = df.groupby('column1')['column2'].apply(list).reset_index()

输出:

    column1                                                       column2
0 MGI:96522 [MP:0001614, MP:0000364, MP:0006093]
1 MGI:97874 [MP:0008796, MP:0009395, MP:0009937, MP:0011098, MP:0011703]

现在您已经聚合了数据框,您可以以任何您想要的格式进行打印。

可能是这样的:

for idx, x in g.iterrows():
print(x['column1'], [y for y in x['column2']])

输出:

MGI:96522 ['MP:0001614', 'MP:0000364', 'MP:0006093']
MGI:97874 ['MP:0008796', 'MP:0009395', 'MP:0009937', 'MP:0011098', 'MP:0011703']

关于python - 如何聚合扩展值 - python - pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51601583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com