首页 > 解决方案 > 计算python数据框中短语的出现次数

问题描述

我有一个这样的df:

names = ["Internal medicine, Gastroenterology", "Internal medicine, Family and general medicine, Endocrinology", "Pediatrics, Medical genetics, Laboratory medicine", "Internal medicine"]
df = pd.DataFrame(names, columns=['names'])

我想知道每个医学术语出现的频率。例如这里

它适用Counter于单词,但我如何让它适用于诸如“内科”之类的短语?“,”分隔短语。

标签: pythonpandasstringdataframecount

解决方案


如果你想使用collections.Counter,你可以这样做:

In [1945]: from collections import Counter

In [1946]: d = Counter(df['names'].str.split(", ").explode().tolist())

In [1947]: d
Out[1947]: 
Counter({'Internal medicine': 3,
         'Gastroenterology': 1,
         'Family and general medicine': 1,
         'Endocrinology': 1,
         'Pediatrics': 1,
         'Medical genetics': 1,
         'Laboratory medicine': 1})

推荐阅读