I want to count number of times each values is appearing in dataframe.
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
I want to dictionary of counts:
ex. counts = {N: 14, C:2, S:4}
I have tried df['status']['N']
but it gives keyError
and also df['status'].value_counts
but no use.
Using the size() or count() method with pandas. DataFrame. groupby() will generate the count of a number of occurrences of data present in a particular column of the dataframe.
You can use the nunique() function to count the number of unique values in a pandas DataFrame.
To create a frequency column for categorical variable in an R data frame, we can use the transform function by defining the length of categorical variable using ave function. The output will have the duplicated frequencies as one value in the categorical column is likely to be repeated.
count() function is used to count occurrences of pattern in each string of the Series/Index. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the Series. Valid regular expression. For compatibility with other string methods.
You can use value_counts
and to_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}
An alternative one liner using underdog Counter
:
In [3]: from collections import Counter In [4]: dict(Counter(df.status)) Out[4]: {'C': 2, 'N': 14, 'S': 4}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With