str.count()

Pandas

Number of occurences of pattern in a string .
Returns Series or Index

Options

pattern ( required ) : Pattern to search in string
flag : (optional ) : we can use re module.
import pandas as pd 
my_dict={'NAME':['Ravi','Raju','Alex']}
df = pd.DataFrame(data=my_dict)
print(df.NAME.str.count(pat='a'))
Output
0    1
1    1
2    0
Here we have searched for a and returned number of occurences.

Let us display by adding a column.
import pandas as pd 
my_dict={'NAME':['Ravi','Raju','Alex']}
df = pd.DataFrame(data=my_dict)
df['number']=df.NAME.str.count(pat='a')
print(df)
Output
   NAME  number
0  Ravi       1
1  Raju       1
2  Alex       0

Flag

Let us match pattern with case insensitive.
import pandas as pd 
import re 
my_dict={'NAME':['Ravi','Raju','Alex']}
df = pd.DataFrame(data=my_dict)
df['number']=df.NAME.str.count('r', re.I)
print(df)
Output
   NAME  number
0  Ravi       1
1  Raju       1
2  Alex       0
In above code we have included re module and this is a case insensitive pattern matching.

Escaping characters

To search some characters need to be escaped.
import pandas as pd 
my_dict={'NAME':['Ravi$a','Raj$u$b','Alex']}
df = pd.DataFrame(data=my_dict)
df['number']=df.NAME.str.count(pat='\$')
print(df)
Output
      NAME  number
0   Ravi$a       1
1  Raj$u$b       2
2     Alex       0

Counting the total occurrence of sub-string in column

import pandas as pd 
df = pd.DataFrame(['John','Mac','Arnold','Krish','Roni'],
                  columns=['Names'])  
df.Names.str.count('r')	
Output is here
0    0
1    0
2    1
3    1
4    0
We will use sum() to get total matching substrings.
df.Names.str.count('r').sum()
Output is
2
Pandas contains() Converting char case slice() split()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer