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
Pandas contains() Converting char case slice() split()


plus2net.com



Post your comments , suggestion , error , requirements etc here




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