TypeError:“float”类型的对象没有len()&TypeError:“float”对象不是iterab

2024-03-28 13:30:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集作为DataFrame“new_data_words”导入。有一个“页面名称”列,其中包含杂乱的页面名称,如“%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”,以便在页面名称中包含单词计数(单词由“u”分隔)

以下是我的代码:

分词:

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

我检查了b的类型是list类型,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"]))

看来名单上有些不正常的东西。但我不知道那是什么,也不知道如何找到它。

有人能帮忙吗?


Tags: in名称列表newfordatalenrange
1条回答
网友
1楼 · 发布于 2024-03-28 13:30:21

你错了。您看到的错误100%清楚地表明b是一个至少包含一个float的iterable(其他元素是否是str,我不作推测)。

试着做:

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

你会看到至少有一个float。或者只打印b的不可iterable组件:

import collections

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

相关问题 更多 >