gpt4 book ai didi

python - 在 Python 中按唯一值对列进行分组

转载 作者:太空宇宙 更新时间:2023-11-03 14:05:03 25 4
gpt4 key购买 nike

我有一个包含两列的数据集,我需要将其更改为以下格式:

10  1 
10 5
10 3
11 5
11 4
12 6
12 2

对此

10  1  5  3
11 5 4
12 6 2

我需要第一列中的每个唯一值都在其自己的行中。

我是 Python 的初学者,除了阅读我的文本文件之外,我不知道如何继续。

最佳答案

您可以使用 Pandas 数据框。

import pandas as pd

df = pd.DataFrame({'A':[10,10,10,11,11,12,12],'B':[1,5,3,5,4,6,2]})
print(df)

输出:

    A  B
0 10 1
1 10 5
2 10 3
3 11 5
4 11 4
5 12 6
6 12 2

让我们使用groupbyjoin:

df.groupby('A')['B'].apply(lambda x:' '.join(x.astype(str)))

输出:

A
10 1 5 3
11 5 4
12 6 2
Name: B, dtype: object

关于python - 在 Python 中按唯一值对列进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606413/

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