【问题标题】:Counting unique words in a pandas column计算熊猫列中的唯一单词
【发布时间】:2020-10-20 23:53:21
【问题描述】:

我在处理以下数据时遇到了一些困难(来自 pandas 数据框):

Text
0   Selected moments from Fifa game t...
1   What I learned is that I am ...
3   Bill Gates kept telling us it was comi...
5   scenario created a month before the...
... ...
1899    Events for May 19 – October 7 - October CTOvision.com
1900    Office of Event Services and Campus Center Ope...
1901    How the CARES Act May Affect Gift Planning in ...
1902    City of Rohnert Park: Home
1903    iHeartMedia, Inc.

我需要提取每行唯一单词的计数(删除标点符号后)。所以,例如:

Unique
0   6
1   6
3   8
5   6
... ...
1899    8
1900    8
1901    9 
1902    5
1903    2

我尝试如下:

df["Unique"]=df['Text'].str.lower()
df["Unique"]==Counter(word_tokenize('\n'.join( file["Unique"])))

但我没有任何计数,只有一个单词列表(没有它们在该行中出现的频率)。

你能告诉我有什么问题吗?

【问题讨论】:

标签: python pandas counter


【解决方案1】:

如果不需要计算,请先删除所有标点符号。杠杆套。 str.split.map(set) 会给你一套。之后计算集合中的元素。集合不包含多个唯一元素。

链式

df['Text'].str.replace(r'[^\w\s]+', '').str.split().map(set).str.len()

逐步

df[Text]=df['Text'].str.replace(r'[^\w\s]+', '')
df['New Text']=df.Text.str.split().map(set).str.len()

【讨论】:

  • 这包括连字符在内的标点符号
  • @David Erickson,剥离它们
  • strip 只删除多余的空格而不是标点符号。
  • @David Erickson ` df[Text]=df['Text'].str.replace(r'[^\w\s]+', '')`
  • 顺便说一句,我认为这是一个很好的答案,所以不要误会我的意思。我认为提取物有点清洁,所以我很想知道是否有人知道如何做到这一点。由于句子中间的标点符号和数字,Extract 可能不适用于此类问题,因此最好只替换它们。我在互联网上没有看到任何关于提取此问题的信息。
【解决方案2】:

所以,我只是根据 cmets 更新它。此解决方案也考虑了标点符号。

df['Unique'] =  df['Text'].apply(lambda x: x.translate(str.maketrans('', '', string.punctuation)).strip()).str.split(' ').apply(len)

【讨论】:

  • 这包括连字符在内的标点符号,与 wwnde 的答案几乎相同。
  • 是的,本质上是一样的。当我看到这个问题时,他的答案没有发布。让我通过考虑标点符号来扩展它。
  • 任一解决方案都有效。虽然在我看来 wwnde 更整洁。
  • string 库很好的一个
  • @annicheez,你的回答也很好,很抱歉只标记一个。但我之前也给了你我的投票,因为它非常好而且很有帮助。我真的很感谢你的帮助。非常感谢。
【解决方案3】:

试试这个

from collections import Counter

dict = {'A': {0:'John', 1:'Bob'},
        'Desc': {0:'Bill ,Gates Started Microsoft at 18 Bill', 1:'Bill Gates, Again .Bill Gates  and Larry Ellison'}}

df = pd.DataFrame(dict)
df['Desc']=df['Desc'].str.replace(r'[^\w\s]+', '')
print(df.loc[:,"Desc"])
 
print(Counter(" ".join(df.loc[0:0,"Desc"]).split(" ")).items())
print(len(Counter(" ".join(df.loc[0:0,"Desc"]).split(" ")).items()))

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2022-01-18
    • 2016-07-01
    • 1970-01-01
    • 2019-02-12
    • 2018-03-19
    • 2018-04-29
    • 1970-01-01
    • 2019-02-12
    相关资源
    最近更新 更多