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
相关产品推荐
相关产品推荐

