如何使用python计算数据帧中列中每行上某些字符串/单词的外观
如何计算数据帧中列中每行上某些字符串/单词的外观 例如:如何使用python计算数据帧中列中每行上某些字符串/单词的外观,python,dataframe,Python,Dataframe,如何计算数据帧中列中每行上某些字符串/单词的外观 例如: column ================================================= I am not hungry He does not angry I believe him I can not believe that he does not believe me 然后我想得到每行中出现的单词“not”的总数。我想得到的是: column
column
=================================================
I am not hungry
He does not angry
I believe him
I can not believe that he does not believe me
然后我想得到每行中出现的单词“not”的总数。我想得到的是:
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
这是您的代码片段
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)
这是输出
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
如果您愿意,可以使用这一行代码-
df['count word "not"'] = df['column'].apply(lambda x : len([c for c in x.split(' ') if c == 'not']))