You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas读取Excel时如何为缺失的预期列填充NULL?

解决方法

方案一:先校验列再读取(高效适合大文件)

先获取工作表的列名,筛选出实际存在的目标列读取,再补全缺失列并填充NULL:

import pandas as pd

# 定义需要读取的目标列
target_cols = ['SEQ ID', 'NAME', 'AGE']

# 打开Excel文件,避免重复读取提升效率
xls = pd.ExcelFile(wb_data)
# 读取表头行获取所有列名
sheet_cols = pd.read_excel(xls, sheet_name="Premises Evaluation", nrows=0).columns.tolist()
# 筛选出目标列中实际存在的列
existing_cols = [col for col in target_cols if col in sheet_cols]

# 读取存在的列
df = pd.read_excel(
    xls,
    index_col=None,
    na_values=['NA'],
    sheet_name="Premises Evaluation",
    usecols=existing_cols
)

# 补全缺失列,用NULL填充
for col in target_cols:
    if col not in df.columns:
        df[col] = pd.NA

方案二:直接读取后重新索引(简洁适合小文件)

读取工作表所有列,再通过reindex对齐到目标列,缺失列自动填充NaN(对应SQL的NULL):

import pandas as pd

target_cols = ['SEQ ID', 'NAME', 'AGE']

xls = pd.ExcelFile(wb_data)
df = pd.read_excel(
    xls,
    index_col=None,
    na_values=['NA'],
    sheet_name="Premises Evaluation"
).reindex(columns=target_cols)

内容的提问来源于stack exchange,提问作者Lee Murray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 15:45:55