TypeError: 'float' object is not iterable for dataframe

问题描述 投票:0回答:1

为什么给出“浮动”对象不可迭代错误?什么时候放嵌套循环?

text = []

for i in df['text']:

    string = ""
    for j in i:
        string += j
    text.append(string)

text[2]
python pandas object typeerror iterable
1个回答
0
投票

@miepsik 是对的,您可能在

text
列中有 NaN。

可重现的例子:

df = pd.DataFrame({'text': ['Hello', np.nan, 'World']})

text = []
for i in df['text']:
    string = ""
    for j in i:
        string += j
    text.append(string)

输出:

...
TypeError: 'float' object is not iterable

要调试数据框并找到 NaN 值,您可以使用:

>>> df.loc[df['text'].isna()]
  text
1  NaN

我的理解是你迭代字符串(

i
)然后循环每个字符(
j
)并创建一个列表。我不确切知道你的数据框是什么样子,但你可以使用矢量化函数优化你的代码,例如:

>>> df['text'].dropna().tolist()
['Hello', 'World']
© www.soinside.com 2019 - 2024. All rights reserved.