.apply()抛出TypeError:类型为' float'的对象没有len()

时间:2018-01-22 11:30:01

标签: python pandas

我试图在local.properties列中填写字段的长度并存储到新列中,但它会抛出此错误item_description

代码:

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

当我在df['desc_len']=df['item_description'].apply(len) 字段(name上运行它,因为它们都是dtype)时,它运行时没有错误。 我错过了什么?

object是一个DataFrame

2 个答案:

答案 0 :(得分:1)

如果要获得某些可迭代的length,例如list s,请使用str.len更为通用的apply(len)

df['desc_len']=df['item_description'].str.len()

您的解决方案:

df['desc_len']=df['item_description'].apply(len)

在理想数据中工作得很好 - 只能迭代。但如果混合 - 可迭代和标量会引起错误。

答案 1 :(得分:0)

我不确定.str.len()会起作用。我建议:

df['desc_len'] = df['item_description'].apply(str).apply(len)