首页 > 解决方案 > 从字典列表创建数据帧时,间歇性“TypeError:'float'类型的对象没有len()”

问题描述

我认为我的解决方案并不完全是我的解决方案

“解决方案”代码:

# Get "raw" data
orig_df = pd.DataFrame(list(jobs["jobs_by_id"]))

# Creates df but removes the NaN elements
new_df = pd.DataFrame(list(orig_df[0]).dropna())   

# Get the orig_df indexes of non-NaN rows to apply to the new df
new_ndx = new_df.index[orig_df[0].notna()]

# Reset index and give new indexes that will line up
new_df = new_df.reset_index(drop=True)
new_df = new_df.set_index(new_ndx)

# Now apply the new_df to the orig_df
orig_df= pd.concat([orig_df, new_df ], axis=1)

现在我遇到了断断续续的TypeError: object of type 'float' has no len(). 上面代码示例的第一行会引发此错误。有时代码按预期运行,有时会抛出TypeError.

找到了这篇文章并按照答案的建议做了,打印出列/系列中的每个元素,看看它是什么类型。我知道一些行/元素将是空的,并且将包含NaN. 两组作业步骤都有NaN系列中的元素,但有些过程很好,而另一些则出错。成功和错误批处理都包含字典列表 NaN. 两个数据集中都没有格式错误的字典,并且所有数据类型都符合预期。

这个作业批处理执行得很好:

Processing  JOB_123456
<class 'float'>
<class 'float'>
<class 'float'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'float'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
SUCCESS 

然而这一...

Processing  JOB_99999
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'float'>
<class 'float'>
<class 'list'>
<class 'float'>
Traceback (most recent call last):
  File "jobs.py", line 743, in <module>
    dump_events('2021-04-13')
  File "jobs.py", line 198, in job_events
    orig_df = pd.DataFrame(list(jobs["jobs_by_id"]))
  File "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/pandas/core/frame.py", line 450, in __init__
    arrays, columns = to_arrays(data, columns, dtype=dtype)
  File "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/pandas/core/internals/construction.py", line 464, in to_arrays
    return _list_to_arrays(data, columns, coerce_float=coerce_float, dtype=dtype)
  File "/opt/rh/rh-python36/root/usr/lib64/python3.6/site-packages/pandas/core/internals/construction.py", line 496, in _list_to_arrays
    content = list(lib.to_object_array(data).T)
  File "pandas/_libs/lib.pyx", line 2275, in pandas._libs.lib.to_object_array
TypeError: object of type 'float' has no len()

为什么 python 只在某些情况下不开心?

标签: pythonpandasdataframetypeerror

解决方案


这是您可以用来调试代码的方法 -

在代码的第 198 行之前再添加一行以检查 'jobs['jobs_by_id]' 的数据类型

print(type(jobs["jobs_by_id"])) # line to add
orig_df = pd.DataFrame(list(jobs["jobs_by_id"]))

在脚本成功运行的第一次运行中,您可能会将数据类型设为“列表”。但是,在第二次运行时,对于某些实例,数据类型可能是“浮动”,这就是您收到此错误的原因。

您可能需要在代码中添加一些错误处理来解决问题。


推荐阅读