首页 > 解决方案 > 在 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

我不知所措。我会很感激任何建议接下来要尝试什么。

标签: pythonpandas

解决方案


我遇到了同样的问题。正如您在pandas.errors.DtypeWarning 的源代码中看到的那样,它是从Warning类继承的。在 python 中,不会捕获警告。我检查了这篇博文,发现我们可以使用

import pandas as pd
import warnings
warnings.simplefilter('error', pd.errors.DtypeWarning)

视为DtypeWarning例外。然后,try ... except ...可以工作了。


推荐阅读