Reputation: 349
How to count the appearances of certain string/words on each row in a column in a dataframe?
for example:
column
=================================================
I am not hungry
He does not angry
I believe him
I can not believe that he does not believe me
then i want to get the total of word "not" appeared in each row. What i want to get is:
column |count word "not"
=================================================|================
I am not hungry | 1
He does not angry | 1
I believe him | 0
I can not believe that he does not believe me | 2
Upvotes: 0
Views: 90
Reputation: 65
You can use this one liner code if you like -
df['count word "not"'] = df['column'].apply(lambda x : len([c for c in x.split(' ') if c == 'not']))
Upvotes: 0
Reputation: 375
Here is your code snippet ,
import pandas as pd
import numpy as np
df1 = {
'Column':['I am not hungry','He does not angry','I believe him','I can not believe
that he does not believe me'],'Count':['0','0','0','0']}
df1 = pd.DataFrame(df1,columns=['Column','Count'])
for ind in df1.index:
df1['Count'][ind] = df1['Column'][ind].count('not')
print(df1)
and here is the output
Column Count
0 I am not hungry 1
1 He does not angry 1
2 I believe him 0
3 I can not believe that he does not believe me 2
Upvotes: 1