Frequency table for a single variable

今天的最后一个新手熊猫问题: 如何为单个 Series 生成表?

例如:

my_series = pandas.Series([1,2,2,3,3,3])
pandas.magical_frequency_function( my_series )


>> {
1 : 1,
2 : 2,
3 : 3
}

Lots of googling has led me to Series.describe() and pandas.crosstabs, but neither of these does quite what I need: one variable, counts by categories. Oh, and it'd be nice if it worked for different data types: strings, ints, etc.

145083 次浏览

也许是 .value_counts()

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

你可以在数据框架上使用列表内涵来计算列的频率

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]

细目:

my_series.select_dtypes(include=['O'])

只选择分类数据

list(my_series.select_dtypes(include=['O']).columns)

将上面的列转换为列表

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]

遍历上面的列表,并对每个列应用 value _ count ()

由@DSM 提供的答案简单明了,但是我想我应该对这个问题加入我自己的意见。如果您查看 Value _ count的代码,您将看到有许多事情正在发生。

如果您需要计算许多序列的频率,这可能需要一段时间。更快的实现方式是将 笨笨,独一无二return_counts = True一起使用

这里有一个例子:

import pandas as pd
import numpy as np


my_series = pd.Series([1,2,2,3,3,3])


print(my_series.value_counts())
3    3
2    2
1    1
dtype: int64

请注意,这里返回的项是熊猫

In comparison, numpy.unique returns a tuple with two items, the unique values and the counts.

vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]

You can then combine these into a dictionary:

results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}

And then into a pandas.Series

print(pd.Series(results))
1    1
2    2
3    3
dtype: int64

对于频率分布的变量与过多的值 你可以折叠类中的值,

这里我为 employrate变量的值过多,它的频率分布与直接 values_count(normalize=True)没有意义

                country  employrate alcconsumption
0           Afghanistan   55.700001            .03
1               Albania   11.000000           7.29
2               Algeria   11.000000            .69
3               Andorra         nan          10.17
4                Angola   75.699997           5.57
..                  ...         ...            ...
208             Vietnam   71.000000           3.91
209  West Bank and Gaza   32.000000
210         Yemen, Rep.   39.000000             .2
211              Zambia   61.000000           3.56
212            Zimbabwe   66.800003           4.96


[213 rows x 3 columns]

频率分布与 values_count(normalize=True)没有分类,结果长度在这里是139(似乎没有意义的频率分布) :

print(gm["employrate"].value_counts(sort=False,normalize=True))


50.500000   0.005618
61.500000   0.016854
46.000000   0.011236
64.500000   0.005618
63.500000   0.005618


58.599998   0.005618
63.799999   0.011236
63.200001   0.005618
65.599998   0.005618
68.300003   0.005618
Name: employrate, Length: 139, dtype: float64

我们把所有的值放在一定的范围内。

0-10 as 1,
11-20 as 2
21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
(gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
)
print(gm["employrate"].value_counts(sort=False,normalize=True))

分类后,我们有一个明确的频率分布。 在这里我们可以很容易地看到,国家的 37.64%51-60%之间有雇佣率 国家的 11.79%71-80%之间的就业率

5.000000   0.376404
7.000000   0.117978
4.000000   0.179775
6.000000   0.264045
8.000000   0.033708
3.000000   0.028090
Name: employrate, dtype: float64