繁体   English   中英

类型错误:'float' 类型的 object 没有 len() - NLP

[英]TypeError: object of type 'float' has no len() - NLP

我正在尝试创建一个具有文本长度的变量。 我正在使用下面的代码:

messages['length']=messages['Review Text'].apply(len)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-fa1723bfb3a3> in <module>
----> 1 messages['length']=messages['Review Text'].apply(len)

~\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   4136             else:
   4137                 values = self.astype(object)._values
-> 4138                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   4139 
   4140         if len(mapped) and isinstance(mapped[0], Series):

pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()

TypeError: object of type 'float' has no len()

我应该怎么做才能解决这个问题?

仔细检查您的数据。 消息"TypeError: object of type 'float' has no len()"让我相信'Review Text'中至少有一个单元格不是文本值,而是浮点值。

设置一个简单的例子:

df = pd.DataFrame([{'str': 'free peoples of middle earth'}])

只需调用获取字符串向量长度的方法即可。

df['str'].str.len()

0    28
Name: str, dtype: int64

如果您有非字符串元素,那么您要么需要在使用 Series.str 之前使用Series.str astype(str)将它们转换为字符串,要么如果您有NaN ,则在获取长度后在 output 列上使用fillna(0) ,无论您放在哪里它。 当然,除非您不想用数据填充它们,因为NaN会传播。

编辑。 您收到错误消息说浮点数没有长度的原因是因为您的数据中有NaN 例如

df = pd.DataFrame([{'str': 'free peoples of middle earth'}, {'str': np.nan}])

df['str'].apply(lambda s: len(s))

... Traceback suppressed
TypeError: object of type 'float' has no len()

但是请注意, Series.str.len() function 处理此问题:

df['str'].str.len()
Out[59]: 
0    28.0
1     NaN
Name: str, dtype: float64

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM