Getting counts of column frequency in a Pandas DataFrame

Counters | Python Methods and Functions

Method # 1: Using Series.value_counts()

This method applies to the pandas.Series object. Since each DataFrame is a collection of a Series object, we can use this method to get the frequency values ​​in a single column.

# import pandas as pd

import pandas as pd

 
# sample data frame

df = pd.DataFrame ({ ' A' : [ 'foo' , ' bar' , 'g2g' , ' g2g' , 'g2g' ,

  ' bar' , 'bar' , 'foo' , 'bar' ],

  ' B' : [ 'a' , 'b' , ' a' , 'b' , ' b' , 'b' , ' a' , 'a' , ' b' ]})

 
# column A count rate

count = df [ 'A' ]. value_counts ()

print (count)

Output:

Method # 2: Using GroupBy.count()

This method can be used to count the frequencies of objects in individual columns. After grouping the DataFrame into a single column, we can apply the count () method to the resulting groupby to get the DataFrame containing the frequency counter.

# import pandas as pd

import pandas as pd

 
# sample data frame

df = pd.DataFrame ({ ' A' : [ 'foo' , 'bar' , ' g2g' , ' g2g' , 'g2g' ,

'bar' , 'bar' , ' foo' , 'bar' ],

'B' : [ 'a' , ' b' , 'a' , ' b' , 'b' , ' b' , 'a' , 'a' , ' b' ]})

  
# Number of frequency columns

count = df.groupby ([ 'A' ]). count ()

print (count)

Output:

Method # 3: Using GroupBy.size()

This method can be used to count the frequencies of objects by one or more columns. After grouping the DataFrame by one or more columns, we can apply the size () method to the resulting groupby object to get a Series object containing the frequency counter.

# import pandas as pd

import pandas as pd

 
# sample data frame

df = pd.DataFrame ({ 'A' : [ ' foo' , 'bar' , ' g2g' , 'g2g' , ' g2g'

'bar' , ' bar' , 'foo' , ' bar' ],

'B' : [ 'a' , ' b' , 'a' , ' b' , 'b' , ' b' , 'a' , 'a' , ' b' ]})

  
# Number of frequency columns

count = df.groupby ([ 'A' , 'B' ]). size ()

print (count)

Output:





Get Solution for free from DataCamp guru