【问题标题】:How to get all unique words on a dataframe如何获取数据框中的所有唯一词
【发布时间】:2018-05-05 23:16:03
【问题描述】:

我正在将评论数据集加载到 pandas 中,作为处理的一部分,我想获取所有独特的词来创建 词袋

由于文本包含在多行中,我首先必须合并它们。

我试过了:

all_text = df['review_body'].to_string()
words = set(a.split(' '))
words = list(words)

但我从那里得到了不正确的词,例如:

u'fel...\n1093'

【问题讨论】:

    标签: python pandas nlp


    【解决方案1】:
    words = " ".join(df.review_body).split()
    

    如果您只想保留唯一的非数字字符串,我建议使用集合理解:

    words = {
        x for x in ' '.join(
            df.review_body.str.lower().tolist()
        ).split() if x.isalpha()
    } 
    

    【讨论】:

      【解决方案2】:

      假设数据框如下:

      df = pd.DataFrame({'review_body': ['This is review 1', 'This is other review 2', 'this is third review 3']})
      print(df)
      

      结果:

                    review_body
      0        This is review 1
      1  This is other review 2
      2  this is third review 3
      

      然后,您可以尝试关注,使用cat,后跟lowersplit

      result = set(df['review_body'].str.cat(sep=' ').lower().split())
      print(result)
      

      结果:

      {'this', 'is', 'third', 'other', '3', 'review', '2', '1'}
      

      【讨论】:

      • 我喜欢你的 cat 解决方案简洁。 ;) 但是,根据我的经验,加入要快一些。
      【解决方案3】:

      只是为了玩耍和提供更多选择:)

      df["review_body"].str.lower().str.split(" ").apply(pd.Series).stack().unique()
      

      即降低并拆分,然后堆叠所有单词并使用unique()

      【讨论】:

        【解决方案4】:

        没有足够的代表发表评论,但除了上面提供的答案之外,您还可以使用正则表达式删除字符串中不需要的字符。

        import re
        string = 'this is a \nstring'
        cleanstring = re.sub('[\n]', '', string)
        

        输出:

        'this is a string'
        

        这将帮助您清理数据以识别真正唯一的单词,而不是将 \nstring 和 string 视为两个不同的单词。

        【讨论】:

        • 这与pandas无关。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-15
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-18
        相关资源
        最近更新 更多