【问题标题】:Tokenizing words in pandas seriespandas 系列中的词分词
【发布时间】:2020-10-28 14:35:58
【问题描述】:

我在熊猫系列中标记单词时遇到问题。

我的系列名为df

                        text
0     This monitor is a great deal for the price.
1     I would recommend it.
2     poor packaging.
dtype: object

我试过df_tokenized=nltk.word_tokenize(df),但结果是TypeError: expected string or bytes-like object

我还尝试了.apply(lambda row:) 的 3 种变体

df_tokenized=df.apply(lambda row: nltk.word_tokenize(row['text']), axis=1)
> TypeError: <lambda>() got an unexpected keyword argument 'axis'

df_tokenized=df.apply(lambda row: nltk.word_tokenize(row['text']))
> TypeError: string indices must be integers

df_tokenized=df.apply(lambda row: nltk.word_tokenize(row[1]))
> TypeError: 'float' object is not subscriptable

还有其他方法来标记系列中的单词吗?

【问题讨论】:

  • 如果您觉得这个答案有用,您能否将问题标记为已回答(答案左侧的灰色勾号)并点赞?

标签: python pandas nlp nltk


【解决方案1】:

我相信您可以使用以下任何一种(这是您引用的第一个):

import nltk
import pandas as pd

df = pd.DataFrame({'text': [' This monitor is a great deal for the price.',
                            'I would recommend it.',
                            'poor packaging.']})
print(df.info())

df_tokenized = df.apply(lambda row: nltk.word_tokenize(row['text']), axis=1)

print(df_tokenized)

还有输出:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   text    3 non-null      object
dtypes: object(1)
memory usage: 152.0+ bytes

     

                                  text
0   This monitor is a great deal for the price.
1                         I would recommend it.
2                               poor packaging.
0    [This, monitor, is, a, great, deal, for, the, ...
1                         [I, would, recommend, it, .]
2                                 [poor, packaging, .]
dtype: object

【讨论】:

  • @Win Wongsawatdichart:如果有帮助,请您批准答案(答案左侧的灰色勾号)?
  • 抱歉回复晚了,我的数据是系列类型,我现在知道series.apply() 中没有轴选择。但是我遇到的下一个问题是TypeError: expected string or bytes-like object 我尝试使用 .str 但它似乎并没有真正起作用。你有什么建议吗?尽管如此,还是非常感谢您的回复,非常感谢。
  • 哦,我想通了,原来我的系列有 NA 值,所以它不能使用该功能。
  • 您可以将 if 子句添加到使用 df.apply 应用的函数中,以便仅在非 NA 值上使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
  • 2014-03-22
  • 2023-03-06
相关资源
最近更新 更多