Python 计算pandas DataFrame列中值的频率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36004976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:15:55  来源:igfitidea点击:

Count frequency of values in pandas DataFrame column

pythondjangopandasdataframe

提问by Kishan

I want to count number of times each values is appearing in dataframe.

我想计算每个值出现在数据框中的次数。

Here is my dataframe - df:

这是我的数据框 - df

    status
1     N
2     N
3     C
4     N
5     S
6     N
7     N
8     S
9     N
10    N
11    N
12    S
13    N
14    C
15    N
16    N
17    N
18    N
19    S
20    N

I want to dictionary of counts:

我想计数字典:

ex. counts = {N: 14, C:2, S:4}

前任。 counts = {N: 14, C:2, S:4}

I have tried df['status']['N']but it gives keyErrorand also df['status'].value_countsbut no use.

我试过了,df['status']['N']但它给了keyError,也df['status'].value_counts没有用。

回答by jezrael

You can use value_countsand to_dict:

您可以使用value_countsto_dict

print df['status'].value_counts()
N    14
S     4
C     2
Name: status, dtype: int64

counts = df['status'].value_counts().to_dict()
print counts
{'S': 4, 'C': 2, 'N': 14}

回答by Colonel Beauvel

An alternative one liner using underdog Counter:

另一种使用 underdog 的班轮Counter

In [3]: from collections import Counter

In [4]: dict(Counter(df.status))
Out[4]: {'C': 2, 'N': 14, 'S': 4}

回答by su79eu7k

You can try this way.

你可以试试这个方法。

df.stack().value_counts().to_dict()

回答by djoguns

See my response in this thread for a Pandas DataFrame output,

有关 Pandas DataFrame 输出,请参阅我在此线程中的回复,

count the frequency that a value occurs in a dataframe column

计算某个值在数据帧列中出现的频率

For dictionary output, you can modify as follows:

对于字典输出,可以修改如下:

def column_list_dict(x):
    column_list_df = []
    for col_name in x.columns:        
        y = col_name, len(x[col_name].unique())
        column_list_df.append(y)
    return dict(column_list_df)

回答by Chuck Logan Lim

Can you convert dfinto a list?

你能转换df成列表吗?

If so:

如果是这样的话:

a = ['a', 'a', 'a', 'b', 'b', 'c']
c = dict()
for i in set(a):
    c[i] = a.count(i)

Using a dict comprehension:

使用字典理解:

c = {i: a.count(i) for i in set(a)}