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 toTrue, the function returns the relative frequencies of the values. It is set toFalseby default.sort(optional): If set toTrue, the function returns the values in a sorted manner. It is set toTrueby default.ascending(optional): If set toTrue, values are sorted in an ascending manner. It is set toFalseby default.bins(optional): Groups values into bins instead of counting them. It is set toNoneby default.dropna(optional): If set toTrue, counts ofNaNare not included. It is set toTrueby default.
Return value
The function returns a series of counts of unique values.
Code
#import libraryimport pandas as pd#define seriess = pd.Series(['Lahore','Murree','Islamabad','Karachi','Lahore','Faislabad','Islamabad'])#print seriesprint(s)
We create a series that contains city names. To get the number of unique cities, we use value_counts().
#print value countsprint(s.value_counts())