简体   繁体   中英

Count how many attributes have a word as a substring of longer text value

For example, if I have a data frame that looks like this:

id    title    
1     assistant
2     chief executive officer
3     director
4     chief operations officer
5     assistant manager
6     producer

If I wanted to find how many title have the word assistant in them, the result should be 2 . If I wanted to find how many title have chief in them, the result should be 2 as well.

Is there a fast way to do this using pandas?

Use str.count with sum :

print (df.title.str.count('chief'))
0    0
1    1
2    0
3    1
4    0
5    0
Name: title, dtype: int64

print (df.title.str.count('chief').sum())
2

print (df.title.str.count('assistant').sum())
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM