我有一个数据集

category
cat a
cat b
cat a

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

category   freq 
cat a       2
cat b       1

当前回答

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

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}

其他回答

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

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}
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)
your data:

|category|
cat a
cat b
cat a

解决方案:

 df['freq'] = df.groupby('category')['category'].transform('count')
 df =  df.drop_duplicates()

@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).fillna(0)

value_counts -返回包含唯一值计数的对象

在每一列中应用计数频率。如果你设置axis=1,你会得到每一行的频率

Fillna(0) -使输出更花哨。更改NaN为0