Home > Backend Development > Python Tutorial > How Can I Count the Frequency of Values in a Pandas DataFrame Column?

How Can I Count the Frequency of Values in a Pandas DataFrame Column?

Linda Hamilton
Release: 2024-12-10 21:22:11
Original
758 people have browsed it

How Can I Count the Frequency of Values in a Pandas DataFrame Column?

Counting Frequency of Values in Dataframe Columns

Given a dataframe with a column containing categorical values, you may encounter the need to count the frequency of occurrence of each unique value.

Consider the following dataframe:

category
cat a
cat b
cat a
Copy after login

To retrieve the distinct values and their corresponding frequencies, follow these steps:

Using value_counts()

As suggested by @DSM, utilize value_counts() to accomplish this task:

In [37]:
df = pd.DataFrame({'a':list('abssbab')})
df['a'].value_counts()
Copy after login

Output:

b    3
a    2
s    2
dtype: int64
Copy after login

Using groupby() and count()

Alternatively, you can employ groupby() and count():

In [38]:
df.groupby('a').count()
Copy after login

Output:

   a
a   
a  2
b  3
s  2

[3 rows x 1 columns]
Copy after login

Additional Options:

For further insight, refer to the pandas documentation at https://pandas.pydata.org.

Incorporating Frequency Back into the Dataframe

If you wish to add the frequency values back to the original dataframe, you can utilize transform() with count():

In [41]:
df['freq'] = df.groupby('a')['a'].transform('count')
df
Copy after login

Output:

   a freq
0  a    2
1  b    3
2  s    2
3  s    2
4  b    3
5  a    2
6  b    3

[7 rows x 2 columns]
Copy after login

The above is the detailed content of How Can I Count the Frequency of Values in a Pandas DataFrame Column?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template