【问题标题】:Count and map number of appearances of strings计算和映射字符串出现的次数
【发布时间】:2019-04-09 08:51:02
【问题描述】:

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

我尝试将 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) 替换为出现次数,例如上面显示的所需输出。

【问题讨论】:

标签: python pandas count python-applymap


【解决方案1】:

而不是测试列表中的项目:

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

你应该使用:

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

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2012-02-12
    相关资源
    最近更新 更多