繁体   English   中英

TypeError:“ float”类型的对象没有len()&TypeError:“ float”对象不可迭代

[英]TypeError: object of type 'float' has no len() & TypeError: 'float' object is not iterable

我有一个导入为DataFrame“ new_data_words”的数据集。 有一列“ page_name”包含凌乱的网页名称,例如“ %D8%AA%D8%B5%D9%86%D9%8A%D9%81:%D8%A2%D9%84%D9... ”, “ %D9%85%D9%84%D9%81:IT-Airforce-OR2.png ”或简称为“ 1950 ”。 我想创建一个新列'word_count'以使页面名称中的单词计数(单词以'_'分隔)

这是我的代码:

拆分为单词:

b = list(new_data_words['page_name'].str.split('_'))
new_data_words['words'] = b

我检查了b的类型是列表类型,len(b)是6035980 一个样本值:

In [1]: new_data_words.loc[0,'words']
Out[2]: ['%D8%AA%D8%B5%D9%86%D9%8A%D9%81:%D8%A2%D9%84%D9%87%D8%A9',
         '%D8%A8%D9%84%D8%A7%D8%AF',
         '%D8%A7%D9%84%D8%B1%D8%A7%D9%81%D8%AF%D9%8A%D9%86']

我创建了另一列“ word_count”以对“ words”列的每一行中的列表元素进行计数。 (必须使用循环触摸每一行中的列表元素)

但是我有错误:

x = []
i = []
c = 0
for i in b:    # i is list type, with elements are string, I checked
    c=c+1
    x.append(len(i))

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-c0cf0cfbc458> in <module>()
      6         #y = str(y)
      7     c=c+1
----> 8     x.append(len(i))

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

我不知道为什么它是浮点型的.....

但是,如果我仅添加打印件,它就可以工作

x = []
i = []
c = 0
for i in b:
    c=c+1
    print len(i)
    x.append(len(i))

3
2
3
2
3
1
8
...

但是c = len(x)= 68516,远小于600万。

我试图将元素再次强制为字符串,发生了另一个错误:

x = []
for i in b:
    for y in i:
        y = str(y)
    x.append(len(i))


TypeError                                 Traceback (most recent call last)
<ipython-input-164-c86f5f48b80c> in <module>()
      1 x = []
      2 for i in b:
----> 3     for y in i:
      4         y = str(y)
      5     x.append(len(i))
TypeError: 'float' object is not iterable

我认为我是列表类型并且可迭代...

再说一次,如果我不追加,而仅打印,则可以正常工作:

x = []
for i in b:
    for y in i:
        y = str(y)
    print (len(i))

另一个例子:

a = []
for i in range(10000):
    a.append(len(new_data_words.loc[i,"words"]))

更改为动态范围,它不起作用:

a = []
for i in range(len(b)):
    a.append(len(new_data_words.loc[i,"words"]))


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-f9d0af3c448f> in <module>()
      1 a = []
      2 for i in range(len(b)):
----> 3     a.append(len(new_data_words.loc[i,"words"]))

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

这也不起作用......

a = []
for i in range(6035980):
    a.append(len(new_data_words.loc[i,"words"]))

似乎列表中有一些异常。 但是我不知道那是什么或如何找到它。

有人可以帮忙吗?

你错了。 您所看到的错误使100%清楚地知道b是一个至少包含一个float的可迭代(无论其他元素是否为str ,我都不会推测)。

尝试做:

for i in b:
    print(type(i), i)

而且您会看到至少有一个float 或仅打印b的不可迭代成分:

import collections

for i in b:
    if not isinstance(i, collections.Iterable):
        print(type(i), i)

暂无
暂无

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

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