计算pandas中文本列中最常用的短语

2024-04-27 22:52:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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个功能?例如,在上述三个短语中,前三个短语是:

 Andy       3
 toy 2011   2
 pal        2

Tags: 数据notext文本pandas管道记录空间
2条回答

请尝试:

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)]

这是另一种获得答案的方法

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

相关问题 更多 >