如何检测哪个类型的头在熊猫是失败的转换?



由于某种原因,我的大数据框架的类型转换失败,我得到一个错误消息如下:could not convert string to float: 'False'.

现在,由于我有100列,我想检测哪一列的类型转换失败,因此查看traceback:

result = result.astype(pdSchema)
File "C:UsersspideyAppDataRoamingPythonPython39site-packagespandascoregeneric.py", line 5859, in astype
col.astype(dtype=dtype[col_name], copy=copy, errors=errors)
File "C:UsersspideyAppDataRoamingPythonPython39site-packagespandascoregeneric.py", line 5874, in astype
new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)
File "C:UsersspideyAppDataRoamingPythonPython39site-packagespandascoreinternalsmanagers.py", line 631, in astype
return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
File "C:UsersspideyAppDataRoamingPythonPython39site-packagespandascoreinternalsmanagers.py", line 427, in apply
applied = getattr(b, f)(**kwargs)
File "C:UsersspideyAppDataRoamingPythonPython39site-packagespandascoreinternalsblocks.py", line 673, in astype
values = astype_nansafe(vals1d, dtype, copy=True)
File "C:UsersspideyAppDataRoamingPythonPython39site-packagespandascoredtypescast.py", line 1097, in astype_nansafe
return arr.astype(dtype, copy=True)
ValueError: could not convert string to float: 'False'

我可以确定值是'False',但我不能确定它在哪个列失败,因为我的多个列有类似的值,为了处理这个异常,我想知道它失败的列名。

我认为pdSchema是字典,所以你可以测试它:

for k, v in pdSchema.items():
try:
result[k].astype(v)
except ValueError:
print (f'Column {k} failed for converting to {v}')

最新更新