【问题标题】:count occurrences of phrases in a python dataframe计算python数据框中短语的出现次数
【发布时间】:2021-02-25 05:43:52
【问题描述】:

我有一个这样的 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'])

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

  • 内科:3个
  • 胃肠病学:1

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

【问题讨论】:

    标签: python pandas string dataframe count


    【解决方案1】:

    split , 然后explode 然后value_counts

    df['names'].str.split(", ").explode().value_counts()
    

    【讨论】:

    • 应该是 split(", ") 否则会记错,但非常感谢! 5 分钟内接受
    【解决方案2】:

    如果你想使用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})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-09
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多