使用 pandas 忽略来自 openpyxl 的 UserWarning

Ignore UserWarning from openpyxl using pandas

我有大量的 .xlsm 文件需要加载。每个 Excel 文件有 6 张。因此,我打开每个 Excel 文件,使用 pandas:

for excel_file in files_list:
    with pd.ExcelFile(excel_file, engine = "openpyxl") as f:
        df1 = pd.read_excel(f, "Sheet1")
        df2 = pd.read_excel(f, "Sheet2")
        df3 = pd.read_excel(f, "Sheet3")
        ...

在每次迭代后,我将 df 传递给其他函数并用它做一些事情。我正在使用 pd.ExcelFile 将文件加载到内存中一次,然后在 DataFrames 上将其分离。

但是,在执行此操作时,我收到以下警告:

/opt/anaconda3/lib/python3.8/site-packages/openpyxl/worksheet/_reader.py:300: UserWarning: Data Validation extension is not supported and will be removed
warn(msg)

无论警告如何,信息都会从 Excel 文件中正确加载,并且不会丢失任何数据。将每个 Excel 文件及其所有工作表加载到 df 中大约需要 0.8 秒。如果我在 pandas 上使用默认引擎加载每个 Excel 文件,警告就会消失,但每个文件花费的时间会增加 5 甚至 6 秒。

我看到了 this post,但是没有关于如何删除警告的答案,这正是我所需要的,因为一切正常。

如何禁用上述 UserWarning?

您可以使用 warnings 核心模块执行此操作:

import warnings

warnings.filterwarnings('ignore', category=UserWarning, module='openpyxl')

您还可以通过添加参数 module="openpyxl".

来指定您希望为其静音警告的特定模块

请参阅 -- 不同的警告,相同的解决方案 - 因此您在打开本书后将警告恢复为默认值,因为可能还有其他您确实希望看到的警告。

import warnings
warnings.simplefilter("ignore")
wb = load_workbook(path)
warnings.simplefilter("default")