首页 > 解决方案 > 将单词列表与系列进行比较

问题描述

我有一个单词列表,并且我有很大的系列,我想将列表中的每个单词与每个单词出现的行数进行比较。

def example(word_list, Series):
   df['0'].value_counts()

据我所知,上面只计算单词的总数,而不是列表中每个单词出现的行数。示例

- 6 行

房子 - 2 行

标签: pythonpandas

解决方案


df = pd.DataFrame(columns=['data'], data=['what are you doing', 'give me the the file', 'the sun comes up up', 'you and me'])
word_list = ['the', 'up', 'me']
df['words'] = df['data'].str.split().apply(lambda i: list(set(i))) # making sure a word occurs only once per row
all_words = [i for j in df['words'].values.tolist() for i in j]
d = {}
for i in word_list:
    d[i] = all_words.count(i)

d
{'the': 2, 'up': 1, 'me': 2}

即使“the”出现了 3 次,也只有 2 行出现,所以输出为 2


推荐阅读