Count() function in Python – Count occurrence of substring pandas

count() Function in python returns the number of occurrences of substring sub in the string. count() Function in python pandas returns the number of occurrences of substring in the dataframe.  lets see an Example of count() Function in python and count() Function in pandas

Syntax of count Function in python:

str.count(sub, start= 0,end=len(string))

sub – substring to be searched for.

start – start index of the string, Default is 0

end – end index of the string, Default is last index of the string.

 

Example of Count() Function in python for a string:

# Example of count function

string1="This is an Example of Count function in Python !!"
print "Count of Example is :" ,string1.count("Example")

#count function with start and end arguments
print "Count of t Excluding first word is:", string1.count("t",4,len(string1))
  • First count function simply prints the number of occurrence of a substring “Example”.
  • Second count Function takes up the start and end arguments and prints the occurrence of the substring “t”.

So the output will be

Count of Example is : 1
Count of t Excluding first word is: 3

 

 

Count of occurrence of the substring in data frame – count() Function in pandas:

Create dataframe:

#create dataframe

import pandas as pd
d = {'Quarters' : ['quarter1','quarter2','quarter3','quarter4'],
     'Revenue':[23400344.567,54363744.678,56789117.456,4132454.987]}
df=pd.DataFrame(d)
print df

Resultant dataframe will be

count function in python pandas 1

 

In the below example we will count the occurrence of substring “1” in the dataframe

# count of occurrence of substring in dataframe

df['count'] = map(lambda x: x.count("1"), df['Quarters'])
print df

map Function counts the occurrence substring “1” and stores the result in the separate column named count so resultant dataframe will be

count function in python pandas 2

previous count() function in python pandas                                                                                                                next count() function in python pandas