【问题标题】:count top most frequent phrases in a text column in pandas计算 pandas 文本列中最常见的短语
【发布时间】:2020-11-11 20:26:40
【问题描述】:

我有一个带有文本列的 pandas 数据框,其中每条记录有 50 个短语,用“|”分隔我想计算整个数据中的前 50 个短语。例如,考虑数据中的“文本”列在每行中有 4 个短语,由管道分隔。 (真实数据有 50 个短语)。管道前后的空间。

                                        text
       0    "Andy | max min | tea | pal"
       1    "no limit | toy 2011 | hess | mix"
       2    "Andy | Andy | toy 2011| pal"

如何找到前 n 个特征?例如,在上面的前 3 个短语是:

 Andy       3
 toy 2011   2
 pal        2

【问题讨论】:

  • 示例每行仅显示 4 个,并且 | 旁边是否有空格还是不行?
  • @Christian Sloper 这是一个例子,只有真实数据有 50 个短语,是的,管道前后有空格

标签: python pandas count frequency phrase


【解决方案1】:

请尝试:

from collections import Counter
# df["text"] = df["text"].str.split(" | ")
df["text"] = df["text"].apply(lambda x: [s.strip() for s in x.split("|")])
c = Counter([item for row in df.text for item in row])
c.most_common(3)
[('Andy', 3), ('pal', 2), ('toy 2011', 2)]

【讨论】:

    【解决方案2】:

    这是获得答案的另一种方式。

    df['text'].str.lower().str.split('|').explode().str.strip().value_counts().nlargest(3)
    

    【讨论】:

      猜你喜欢
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2015-02-01
      • 1970-01-01
      • 2019-04-25
      • 2015-02-18
      • 1970-01-01
      相关资源
      最近更新 更多