我在我的代码中使用Pandas,并使用下面的代码操作一些数据框:
def exit(exitCode, errorMsg=None, monitor_thread=None):
if exitCode is not None:
logger.error(errorMsg)
logger.error(traceback.format_exc())
sys.exit(exitCode)
try:
results['name'] = results['name'].astype(float).astype(int)
except Exception as e: # catch *all* exceptions
exit("Failed to convert name" + str(e), 8)
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Traceback(最近一次调用最后一次):
文件"DIST\FDmanInfo.py",第206行,in
在主文件中输入"DIST\FDmanInfo.py",第191行
文件"\ local\Python\lib\site-packages\pandas\core\generic.py",第3054行,在astype raise_on_error = raise_on_error,**kwargs)
文件"\ local\Python\lib\site-packages\pandas\core\internals.py",第3189行,在astype中
return self.apply('astype',dtype = dtype,**kwargs)
文件"\ local\Python\lib\site-packages\pandas\core\internals.py",第3056行,在apply applied = getattr(b,f)(**kwargs)
文件 "\本地\ Python的\ LIB \站点包\大熊猫\核心\ internals.py",线路461,在astype值=值,**kwargs)
文件"\ local\Python\lib\site-packages\pandas\core\internals.py",第504行,_astype values = _astype_nansafe(values.ravel(),dtype,copy = True)
文件"\ local\Python\lib\site-packages\pandas\types\cast.py",第531行,在_astype_nansafe中引发ValueError('无法将NA转换为整数')ValueError:无法将NA转换为整数
我想知道哪一行正在解决这个问题,但是我无法在任何地方找到异常打印它(行)的日志,就像输入数据帧一样:
Run Code Online (Sandbox Code Playgroud)name0 1.0
1 NaN
2 3.0
3 4.0
我希望它在它失败的行上打印,在这种情况下"1 NaN",它甚至可能吗?
谢谢,
您可以使用内置的python库,回溯
import traceback
try:
results['name'] = results['name'].astype(float).astype(int)
except Exception as e: # catch *all* exceptions
tb = traceback.format_exc()
print(tb)
exit("Failed to convert name" + str(e), 8)
def exit(exitCode, errorMsg=None, monitor_thread=None):
if exitCode is not None:
logger.error(errorMsg)
logger.error(traceback.format_exc())
sys.exit(exitCode)
Run Code Online (Sandbox Code Playgroud)
更新 检查回溯如何工作的简单示例:
import traceback
try:
a = [] + None
except Exception as e:
tb = traceback.format_exc()
print(tb)
exit("Failed to convert name" + str(e))
def exit(exitCode):
print(exitCode)
print(traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |