Python | Pandas Series.str.count ()

Counters | File handling | Python Methods and Functions | Regular Expressions

str.count() Pandas str.count() is used to count occurrences of a string or regular pattern expressions in each line of the series. Additional flag arguments can also be passed for processing to modify some aspects of the

Example # 1: counting occurrences of a word
In this example, the Pandas series is composed of a list and the gfg entry is counted using the str.count () method.

# import pandas package

import pandas as pd

# making a list

list = [ "GeeksforGeeks" , "Geeksforgeeks" , "pythonengineering" ,

"pythonengineering is a great platform " , " for tech geeks " ]

# create series

series = pd.Series ( list )

# counting geeks

count = series. str . count ( "geeks" )

# display

Exit :
As shown in the output image, the appearance of the geeks Inds in each line were displayed, and geeks were not counted due to the first capital letter. 

Example # 2. Using flags

In this example, the occurrence of "a" is counted in the "Name" column. The flag parameter is also used, and re.I is passed to it, which means IGNORECASE. Therefore, a and A will both count towards the count.

# pandas module import

import pandas as pd

# importer for regular expressions

import re

# read CSV file from URL

data = pd.read_csv ( " /nba.csv " )

# String to search at the beginning of the line

search = "a"

# amount occurrences and creating a new column

data [ "count" ] = data [ " Name " ]. str . count (search, re.I)

# display

As shown in the output image, it can be clearly compared by looking at the first index itself. Avery Bradely's A counter is 2, which means both upper and lower case were counted. 

Get Solution for free from DataCamp guru