python - 对 Pandas DataFrame 中的部分字符串(关键字)匹配求和

标签 python pandas

假设我有一个关键字列表(大约 300 个)

Key Word
abduct
attack
airstrike
bomb

我想迭代整个 DataFrame 的 (df1) 列(文本),以便找到出现关键字的任何实例。我的最终目标是获得每个关键词的总计数。

Text                                Location     Date 
Police have just discovered a bomb. New York    4/30/2015, 23:54:27  
...

我知道我可以使用 str.contains (见下文)单独查找每个单词的总数,但我正在寻找一种简单的方法来一次计算总数。

word_count = df1[df1['Text'].str.contains('Key Word').count()

我还尝试使用一个脚本来解决我的问题,该脚本将“文本”中的所有数据拆分为单独的关键字并对总数进行求和,但这没有考虑到任何带有空格的关键字(至少在目前的形式)。

 In [31]: df.Text.str.lower().apply(lambda x: pd.value_counts(x.split(" "))).sum(axis =0)

非常感谢任何帮助!

最佳答案

如果您想要一个可以在计数中包含特定短语(您事先知道的)的解决方案,您可以将短语中的空格替换为另一个字符(例如“_”)。例如:

import pandas as pd
from collections import Counter

df = pd.DataFrame(['Police have discovered an air bomb', 'Air strike the bomb', 'The air strike police are going on strike', 'Air bomb is full of hot air'], columns = ['text'])
keywords = ['bomb', 'police', 'air strike']
keyword_dict = {w:w.replace(' ', '_') for w in keywords}

corpus = ' '.join(df.text).lower()
for w,w2 in keyword_dict.items():
   corpus = corpus.replace(w,w2)

all_counts = Counter(corpus.split())
final_counts = {w:all_counts[w2] for w,w2 in keyword_dict.items()}
print(final_counts)
{'police': 1, 'air strike': 1, 'bomb': 2}

一个更通用的解决方案(从文本挖掘的角度来看可能是更好的实践,您不一定事先知道您要查找的短语),您可以从文本中提取所有二元组并对整个事情:

corpus = ' '.join(df.text).lower()
words = corpus.split()
bigrams = [' '.join([words[i],words[i+1]]) for i in range(len(words) -1)]
print(Counter(words + bigrams))
Counter({'air': 5, 'bomb': 3, 'strike': 3, 'air strike': 2, 'police': 2, 'air bomb': 2, 'the': 2, 'discovered': 1, 'bomb is': 1, 'the bomb': 1, 'have discovered': 1, 'full': 1, 'bomb the': 1, 'going on': 1, 'are going': 1, 'are': 1, 'discovered an': 1, 'the air': 1, 'hot air': 1, 'is full': 1, 'hot': 1, 'on strike': 1, 'is': 1, 'strike the': 1, 'police have': 1, 'bomb air': 1, 'of': 1, 'strike police': 1, 'of hot': 1, 'an': 1, 'strike air': 1, 'on': 1, 'full of': 1, 'police are': 1, 'have': 1, 'going': 1, 'an air': 1})

关于python - 对 Pandas DataFrame 中的部分字符串(关键字)匹配求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30493364/

相关文章:

Python线性回归,残差的最佳拟合线

python - ivot_table() 到 df 没有要聚合的数字类型

Python Pandas : summing value of two or more DataFrames with identical value in multiple columns

python - 删除 +00 :00 (UTC offset) from timestamp in Python/pandas

python - Pandas 表格开始前的数据

python - 取消 pandas 数据框时出错

python - 在循环中逐行填充数组

python - 基维的时间. sleep

python - 在 Keras 中加载模型需要的时间呈指数级增长

python - 在 Python 中计算雅可比矩阵