Calculate the frequency counts of each unique value of a Pandas series
Last Updated :
15 Sep, 2022
Let us see how to find the frequency counts of each unique value of a Pandas series. We will use these methods to calculate the frequency counts of each unique value of a Pandas series.
Using values_counts() to calculate the frequency of unique value
Here values_counts() function is used to find the frequency of unique value in a Pandas series.
Example 1 : Here we are creating a series and then with the help of values_counts() function we are calculating the frequency of unique values.
Python3
import pandas as pd
s = pd.Series(data = [ 2 , 3 , 4 , 5 , 5 , 6 ,
7 , 8 , 9 , 5 , 3 ])
print (s)
print (s.value_counts())
|
Output :
Calculate the frequency counts of each unique value
Example 2 : Here we are randomly generating integer values and then finally calculating the counts for each value.
Python3
import pandas as pd
s = pd.Series(np.take( list ( '0123456789' ),
np.random.randint( 10 , size = 40 )))
s.value_counts()
print (s)
|
Output :
Calculate the frequency counts of each unique value
Example 3 : Here we have a series where each value is a string and we are counting the occurrence of each element in the series.
Python3
import pandas as pd
sr = pd.Series([ 'Mumbai' , 'Pune' , 'Agra' , 'Pune' ,
'Goa' , 'Shimla' , 'Goa' , 'Pune' ])
sr.value_counts()
print (sr)
|
Output :
Calculate the frequency counts of each unique value
Using groupby() to calculate the frequency of unique value
Here we are using the groupby() function to group all the same values and then calculate their frequencies.
Python3
import pandas as pd
technologies = {
"data" :[ 2 , 3 , 4 , 5 , 5 , 6 ,
7 , 8 , 9 , 5 , 3 ]
}
df = pd.DataFrame(technologies)
df[ 'frequency' ] = df.groupby( 'data' )
[ 'data' ].transform( 'count' )
print (df)
|
Output:
Calculate the frequency counts of each unique value
Using apply().fillna() function to calculate the frequency of unique value
Here we are filling NAN or 0 for the None values in the series and apply function to apply the same, and then calculate their frequencies.
Python3
import pandas as pd
technologies = {
"data" :[ 2 , 3 , 4 , 5 , 5 , 6 ,
7 , 8 , 9 , 5 , 3 ]
}
df = pd.DataFrame(technologies)
df1 = df. apply (pd.value_counts).fillna( 0 )
print (df1)
|
Output:
Calculate the frequency counts of each unique value
Share your thoughts in the comments
Please Login to comment...