Pandas DataFrame value_counts() method with examples

Spread the love

Pandas value_counts() method count how many times certain values appear in a column in pandas.

Syntax –

DataFrame.value_counts(subset=None, normalize=False, sort=True, ascending=False, dropna=True)

subset – Columns to use when counting unique combinations.

normalize – Return proportions rather than frequencies.

sort – Sort by frequencies.

ascending – whether to sort in ascending or descending order

dropna – Don’t include counts of rows that contain NA values.

Examples –

Let’s read a dataset to work with.

import pandas as pd

url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/Restaurant.csv'
df = pd.read_csv(url)
df.head()

1 . Count Frequency of each value in a column –

To count the frequency of each value in a column, we can use the value_counts() method in pandas.

df['Quality Rating'].value_counts()
#output
Very Good    150
Good          84
Excellent     66
Name: Quality Rating, dtype: int64

2 . Sort Frequencies in ascending order –

To sort frequencies in ascending order set the ascending parameter to ascending=True.

df['Quality Rating'].value_counts(ascending=True)
#output
Excellent     66
Good          84
Very Good    150
Name: Quality Rating, dtype: int64

3 . Sort Frequencies in descending order –

By default pandas sort frequencies in descending order. If you want you can also set it explicitly by setting the ascending parameter to False.

df['Quality Rating'].value_counts(ascending=False)
#output
Very Good    150
Good          84
Excellent     66
Name: Quality Rating, dtype: int64

4 . Get Proportion instead of Frequencies –

To get Proportion instead of frequencies set the normalize parameter to True.

df['Quality Rating'].value_counts(normalize=True)
#output
Very Good    0.50
Good         0.28
Excellent    0.22
Name: Quality Rating, dtype: float64

Rating: 1 out of 5.

Leave a Reply