What is value_counts() in pandas?

pandas is an open-source Python library that provides operations to analyze and manipulate data structures called data frames. The value_counts() function in pandas returns a series that contains the number of unique values. A series is a one-dimensional array.

Syntax

Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)

Parameters

The value_counts function takes the following parameters:

  • normalize (optional): If set to True, the function returns the relative frequencies of the values. It is set to False by default.
  • sort (optional): If set to True, the function returns the values in a sorted manner. It is set to True by default.
  • ascending (optional): If set to True, values are sorted in an ascending manner. It is set to False by default.
  • bins (optional): Groups values into bins instead of counting them. It is set to None by default.
  • dropna (optional): If set to True, counts of NaN are not included. It is set to True by default.

Return value

The function returns a series of counts of unique values.

Code

#import library
import pandas as pd
#define series
s = pd.Series(['Lahore','Murree','Islamabad','Karachi','Lahore','Faislabad','Islamabad'])
#print series
print(s)

We create a series that contains city names. To get the number of unique cities, we use value_counts().

#print value counts
print(s.value_counts())

Free Resources