【问题标题】:How to get all the unique words in the data frame?如何获取数据框中的所有唯一词?
【发布时间】:2016-07-24 22:50:59
【问题描述】:

我有一个包含产品列表及其各自评论的数据框

+----------+------------------------------------ ------------+
|产品 |评论 |
+---------+-------------------------------------- ---------+
|产品_a |适合休闲午餐|
+---------+-------------------------------------- ---------+
|产品_b |艾弗里是最博学的咖啡师之一 |
+---------+-------------------------------------- ---------+
|产品_c |导游告诉我们秘密|
+---------+-------------------------------------- ---------+

如何获取数据框中的所有唯一词?

我做了一个函数:

def count_words(text):
    try:
        text = text.lower()
        words = text.split()
        count_words = Counter(words)
    except Exception, AttributeError:
        count_words = {'':0}
    return count_words

并将该函数应用于 DataFrame,但这只会给我每行的字数。

reviews['words_count'] = reviews['review'].apply(count_words)

【问题讨论】:

  • 您可以发布您的数据框示例吗?

标签: python pandas dataframe count


【解决方案1】:

从这里开始:

dfx
               review
0      United Kingdom
1  The United Kingdom
2     Dublin, Ireland
3    Mardan, Pakistan

要获取“review”列中的所有单词:

 list(dfx['review'].str.split(' ', expand=True).stack().unique())

   ['United', 'Kingdom', 'The', 'Dublin,', 'Ireland', 'Mardan,', 'Pakistan']

要获得“评论”列的计数:

dfx['review'].str.split(' ', expand=True).stack().value_counts()


United      2
Kingdom     2
Mardan,     1
The         1
Ireland     1
Dublin,     1
Pakistan    1
dtype: int64    ​

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多