我有一个数据集

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

干杯!

其他回答

如果没有任何库,你可以这样做:

def to_frequency_table(data):
    frequencytable = {}
    for key in data:
        if key in frequencytable:
            frequencytable[key] += 1
        else:
            frequencytable[key] = 1
    return frequencytable

例子:

to_frequency_table([1,1,1,1,2,3,4,4])
>>> {1: 4, 2: 1, 3: 1, 4: 2}

你也可以用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
df.category.value_counts()

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

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

df['category'].value_counts()

在0.18.1中,groupby和count没有给出唯一值的频率:

>>> df
   a
0  a
1  b
2  s
3  s
4  b
5  a
6  b

>>> df.groupby('a').count()
Empty DataFrame
Columns: []
Index: [a, b, s]

然而,唯一的值和它们的频率很容易通过大小来确定:

>>> df.groupby('a').size()
a
a    2
b    3
s    2

使用df.a.value_counts(),默认情况下返回排序后的值(降序排列,即最大值在前)。

下面的代码为名为“smaller_dat1”的数据帧中的“Total_score”列中的各种值创建频率表,然后返回值“300”在该列中出现的次数。

valuec = smaller_dat1.Total_score.value_counts()
valuec.loc[300]