在Python中按唯一值对列进行分组 [英] Grouping columns by unique values in Python

查看:106
本文介绍了在Python中按唯一值对列进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的数据集,需要从以下格式进行更改:

I have a data set with two columns and I need to change it from this format:

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

对此

10  1  5  3
11  5  4
12  6  2

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

I need every unique value in the first column to be on its own row.

我是Python的初学者,除了阅读我的文本文件之外,我对如何进行操作一无所知。

I am a beginner with Python and beyond reading in my text file, I'm at a loss for how to proceed.

推荐答案

您可以使用Pandas数据框。

You can use Pandas dataframes.

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

让我们使用 groupby join

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中按唯一值对列进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆