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

标签 python python-2.7 pandas dataframe

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

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/

相关文章:

python - 从 python 中的文本文件中读取带有正则表达式的文件片段

python - 如何将页面的功能连接到 qwizard 的下一步按钮?

python - 无法安装 Pandas -InsecurePlatformWarning错误

python - Pandas read_fwf 特殊字符未正确加载

python - pandas dataframe resample 聚合函数使用具有自定义函数的多列?

python - 为什么导入csv文件时要使用infer_datetime_format?

python - 如何在保持刻度的同时显示刻度标签的特定间隔

python - 我可以让我的类(class)在“关键字”中使用 Python '"吗?

python - 带有 Plotly Dash 的日期 slider 不起作用

python-2.7 - httplib.ResponseNotReady 与 api.ai