简体   繁体   English

有没有一种更简单的方法来用python进行分组和计数?

[英]is there a simpler way to group and count with python?

I am grouping and counting a set of data. 我正在对一组数据进行分组和计数。

df = pd.DataFrame({'key': ['A', 'B', 'A'],
                   'data': np.ones(3,)})
df.groupby('key').count()

outputs 输出

    data
key 
A   2
B   1

The piece of code above works though, I wonder if there is a simpler one. 上面的代码虽然有效,但我想知道是否有一个更简单的代码。

'data': np.ones(3,) seems to be a placeholder and indispensable. 'data': np.ones(3,)似乎是一个占位符,是必不可少的。

pd.DataFrame(['A', 'B', 'A']).groupby(0).count()

outputs 输出

A
B

My question is, is there a simpler way to do this, produce the count of 'A' and 'B' respectively, without something like 'data': np.ones(3,) ? 我的问题是,有没有一种更简单的方法可以分别生成'A'和'B'的计数,而无需像'data': np.ones(3,)这样'data': np.ones(3,)

It doesn't have to be a pandas method, numpy or python native function are also appreciated. 它不必是pandas方法,也可以使用numpy或python native函数。

Use a Series instead. 请改用Series

>>> import pandas as pd
>>> 
>>> data = ['A', 'A', 'A', 'B', 'C', 'C', 'D', 'D', 'D', 'D', 'D']
>>> 
>>> pd.Series(data).value_counts()
D    5
A    3
C    2
B    1
dtype: int64

Use a defaultdict : 使用defaultdict

from collections import defaultdict

data = ['A', 'A', 'B', 'A', 'C', 'C', 'A']

d = defaultdict(int)

for element in data:
    d[element] += 1

d  # output: defaultdict(int, {'A': 4, 'B': 1, 'C': 2})

There's not any grouping , just counting, so you can use 没有任何分组,仅在计数,因此您可以使用

from collections import Counter
counter(['A', 'B', 'A'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM