gpt4 book ai didi

python-3.x - 在 Pandas 中使用 groupby 获取行数

转载 作者:行者123 更新时间:2023-12-03 08:28:40 26 4
gpt4 key购买 nike

我的数据集中有两列,col1col2。我想显示按 col1 分组的数据。

为此,我编写了如下代码:

grouped = df[['col1','col2']].groupby(['col1'], as_index= False)

上面的代码创建了 groupby 对象。

如何使用对象显示按col1分组的数据?

最佳答案

要按group获取计数,可以使用dataframe.groupby('column').size()

例子:

In [10]:df = pd.DataFrame({'id' : [123,512,'zhub1', 12354.3, 129, 753, 295, 610],
'colour': ['black', 'white','white','white',
'black', 'black', 'white', 'white'],
'shape': ['round', 'triangular', 'triangular','triangular','square',
'triangular','round','triangular']
}, columns= ['id','colour', 'shape'])

In [11]:df
Out[11]:
id colour shape
0 123 black round
1 512 white triangular
2 zhub1 white triangular
3 12354.3 white triangular
4 129 black square
5 753 black triangular
6 295 white round
7 610 white triangular


In [12]:df.groupby('colour').size()
Out[12]:
colour
black 3
white 5
dtype: int64

In [13]:df.groupby('shape').size()
Out[13]:
shape
round 2
square 1
triangular 5
dtype: int64

关于python-3.x - 在 Pandas 中使用 groupby 获取行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22267271/

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