计算列中的字数,将前X存储在新列中

2024-09-26 17:53:40 发布

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

我有这样一个DF:

Doc_ID         Text 
  1            hi hi hi 
  2            hello hello1 hello 
  3            hey hallo

我想计算文本列中的单词数,并将其存储在名为(topXwords)的新列中。 所需输出:

Doc_ID         Text                topXwords  
  1            hi hi hi            hi:3
  2            hello hello1 hello  hello:2, hello1:1
  3            hey hallo           hey:1, hallo:1 

我试过什么?

我尝试将文本列转换为列表:

df["topXwords"] = df["Text"].str.split()

在那之后,我试着在列表上循环,并计算列表中的所有项目。对于1列表,它可以工作,但无法将其存储为新列:

import collections
df["topXwords1"]= collections.Counter(df["topXwords"])
TypeError: unhashable type: 'list'


This fails, but it works in this example: 

xxx = ["a","a","b"]
counter = collections.Counter(xxx)
counter
Out[43]: Counter({'a': 2, 'b': 1})

**我使用counter,因为它只在一个示例中起作用。理想情况下,我想调整顶部关键字的数量。**

非常感谢您的帮助


Tags: text文本idhellodf列表doccounter
2条回答

具有pd.Series.value_counts功能:

In [333]: df["topXwords"] = df.Text.apply(lambda s: pd.Series(s.split()).value_counts().to_dict())

In [334]: df
Out[334]: 
   Doc_ID                Text                  topXwords
0       1            hi hi hi                  {'hi': 3}
1       2  hello hello1 hello  {'hello': 2, 'hello1': 1}
2       3           hey hallo     {'hallo': 1, 'hey': 1}

使用apply

from collections import Counter
import pandas as pd

data = [[1, 'hi hi hi'],
        [2, 'hello hello1 hello'],
        [3, 'hey hallo']]

df = pd.DataFrame(data=data, columns=['Doc_ID', 'Text'])

print(df.Text.str.split().apply(Counter))

输出

0                    {'hi': 3}
1    {'hello': 2, 'hello1': 1}
2       {'hey': 1, 'hallo': 1}
Name: Text, dtype: object

如果只想包含前x个单词,请执行以下操作(在本例中x=1):

df['topXwords'] = df.Text.str.split().apply(lambda x: Counter(x).most_common(1))
print(df)

输出

   Doc_ID                Text     topXwords
0       1            hi hi hi     [(hi, 3)]
1       2  hello hello1 hello  [(hello, 2)]
2       3           hey hallo    [(hey, 1)]

相关问题 更多 >

    热门问题