我有一个数据集

category
cat a
cat b
cat a

我希望能够返回(显示唯一值和频率)

category   freq 
cat a       2
cat b       1

当前回答

@metatoaster已经指出了这一点。 去柜台。它的速度非常快。

import pandas as pd
from collections import Counter
import timeit
import numpy as np

df = pd.DataFrame(np.random.randint(1, 10000, (100, 2)), columns=["NumA", "NumB"])

计时器

%timeit -n 10000 df['NumA'].value_counts()
# 10000 loops, best of 3: 715 µs per loop

%timeit -n 10000 df['NumA'].value_counts().to_dict()
# 10000 loops, best of 3: 796 µs per loop

%timeit -n 10000 Counter(df['NumA'])
# 10000 loops, best of 3: 74 µs per loop

%timeit -n 10000 df.groupby(['NumA']).count()
# 10000 loops, best of 3: 1.29 ms per loop

干杯!

其他回答

n_values = data.income.value_counts()

第一个唯一值计数

n_at_most_50k = n_values[0]

第二个唯一值计数

n_greater_50k = n_values[1]

n_values

输出:

<=50K    34014
>50K     11208

Name: income, dtype: int64

输出:

n_greater_50k,n_at_most_50k:-
(11208, 34014)

@metatoaster已经指出了这一点。 去柜台。它的速度非常快。

import pandas as pd
from collections import Counter
import timeit
import numpy as np

df = pd.DataFrame(np.random.randint(1, 10000, (100, 2)), columns=["NumA", "NumB"])

计时器

%timeit -n 10000 df['NumA'].value_counts()
# 10000 loops, best of 3: 715 µs per loop

%timeit -n 10000 df['NumA'].value_counts().to_dict()
# 10000 loops, best of 3: 796 µs per loop

%timeit -n 10000 Counter(df['NumA'])
# 10000 loops, best of 3: 74 µs per loop

%timeit -n 10000 df.groupby(['NumA']).count()
# 10000 loops, best of 3: 1.29 ms per loop

干杯!

如果你想应用到所有列,你可以使用:

df.apply(pd.value_counts)

这将对每一列应用一个基于列的聚合函数(在本例中为value_counts)。

df.category.value_counts()

这一小行代码将提供您想要的输出。

如果列名中有空格,则可以使用

df['category'].value_counts()

你也可以用pandas先把你的列作为类别广播,例如dtype="category"。

cats = ['client', 'hotel', 'currency', 'ota', 'user_country']

df[cats] = df[cats].astype('category')

然后调用describe:

df[cats].describe()

这将给你一个很好的值计数表和更多的东西:):

    client  hotel   currency    ota user_country
count   852845  852845  852845  852845  852845
unique  2554    17477   132 14  219
top 2198    13202   USD Hades   US
freq    102562  8847    516500  242734  340992