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.
Series.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)
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.The function returns a series of counts of unique values.
#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())