python - 在 Pycharm 中捕获 Pandas DtypeWarning
问题描述
对 Python 来说相对较新,在 PyCharm Professional 中处理 Pandas 异常时遇到了挑战。我正在尝试使用 Pandas 读取 CSV:
import pandas as pd
df = pd.read_csv('file.csv', index_col=False)
我收到这条消息:
pydev_umd:1: DtypeWarning: Columns (56) have mixed types. Specify dtype option on import of set low_memory = False
我知道为什么会出现警告。CSV 是另一个程序的输出,该程序很少会省略 CSV 最后一行内部的列,从而导致后续列移动并搞砸 dtypes。我无法更改其他程序的行为,所以我的想法是在 DtypeWarning 发生时在 Python 中添加错误处理。
我对异常没有太多经验,但是在这里看到类似的问题后,我尝试了:
try:
df = pd.read_csv('file.csv', index_col=False)
except pd.errors.DtypeWarning:
print("Handling Dtype warning!")
它似乎没有收到警告;我仍然得到df
相同的信息:
pydev_umd:1: DtypeWarning: Columns (56) have mixed types. Specify dtype option on import of set low_memory = False
我不知所措。我会很感激任何建议接下来要尝试什么。
解决方案
我遇到了同样的问题。正如您在pandas.errors.DtypeWarning 的源代码中看到的那样,它是从Warning
类继承的。在 python 中,不会捕获警告。我检查了这篇博文,发现我们可以使用
import pandas as pd
import warnings
warnings.simplefilter('error', pd.errors.DtypeWarning)
视为DtypeWarning
例外。然后,try ... except ...
可以工作了。
推荐阅读
- python-3.x - IndexError: List Index out of range Keras Tokenizer
- java - Java 对象列表按未排序的特定对象排序
- javascript - 如何使用 php 在不损失质量的情况下增加图像大小
- pdf - 使用 imagemagick 将 pdf 转换为图像并且缺少字体时指定默认替换字体
- excel - 如何根据另一组单元格中的文本更改一个单元格的文本颜色
- python - 使用 Python 抓取 TripAdvisor 酒店页面
- android - com.google.android.gms.common.api.ApiException:16:
- python - 使用python计算gzip文件中的行数
- laravel - Laravel 队列作业保存 Web 服务响应
- c# - Aspnet core 2.1.4 IIS 启动问题