pandas DataFrame 列中值的计数频率

2022-01-31 00:00:00 python pandas dataframe django

问题描述

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

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

这是我的数据框 - df:

Here is my dataframe - 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

我想要计数字典:

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

我试过 df['status']['N'] 但它给出了 keyErrordf['status'].value_counts 但没有用.

I have tried df['status']['N'] but it gives keyError and also df['status'].value_counts but no use.


解决方案

你可以使用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}

相关文章