计数并映射字符串出现的次数

时间:2019-04-09 08:51:02

标签: python pandas count python-applymap

我正在使用Python中的applymap将特定的关键字与文本数据映射。假设我要检查关键字“ hello”与所有行上的文本数据匹配的频率。 Applymap为我提供了所需的矩阵结果,但是只有“ True”或“ False”,而不是出现次数。

我试图将count()与我的applymap函数连接起来,但是我无法使其工作。

最小的工作示例如下:

import pandas as pd
import numpy as np

df = pd.DataFrame({'text': ['hello hello', 'yes no hello', 'good morning']})
keys = ['hello']
keyword = pd.DataFrame({0:keys})

res = []
for a in df['text']:
    res.append(keyword.applymap(lambda x: x in a))

map = pd.concat(res, axis=1).T
map.index = np.arange(len(map))

#Output
map
       0
0   True
1   True
2  False

#Desired Output with 'hello' appearing twice in the first row, once in the second and zero in the third of df.
   0
0  2
1  1
2  0

我正在寻找一种方法来保留我的applymap函数以获取矩阵形式,但将True(1)和False(0)替换为外观数量,例如上面显示的所需输出。

1 个答案:

答案 0 :(得分:1)

代替测试列表中的项目:

res.append(keyword.applymap(lambda x: x in a))#x == a

您应该使用:

res.append(keyword.applymap(lambda x: str.count(a, x)))#计算“ a”的出现

相关问题