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

从Excel提取指定列生成pandas DataFrame:固定无名列+可变位置有名列

实现方案

方案1:为B列设置列名后提取

该方案直接通过pandas原生方法完成,无需额外依赖:

import pandas as pd

# 注意路径前加r防止转义,补全开头的引号
file_location = r'Desktop\Excelfile.xlsx'
# 先仅读取表头行获取列信息
df_header = pd.read_excel(file_location, nrows=0)
# 给固定位置的B列(pandas列索引从0开始,B列对应索引1)设置自定义列名
df_header.columns.values[1] = 'fixed_b_col'
# 替换为你实际的目标列固定名称
target_col = '你的目标列固定名称'
# 按列名筛选读取需要的两列
df = pd.read_excel(
    file_location,
    index_col=None,
    na_values=['NA'],
    usecols=lambda x: x in ['fixed_b_col', target_col]
)

方案2:通过已知列名字符串定位目标列后提取

该方案先定位目标列的Excel列号,再按列位置读取,和你原有代码的读取逻辑更接近:

import pandas as pd
from openpyxl import load_workbook

file_location = r'Desktop\Excelfile.xlsx'
target_col_name = '你的目标列固定名称'
target_col_letter = None

# 只读加载Excel获取表头行信息,内存占用低
wb = load_workbook(file_location, read_only=True, data_only=True)
ws = wb.active
# 遍历第一行表头匹配目标列名,拿到对应的列字母
for col in ws.iter_cols(min_row=1, max_row=1):
    if col[0].value == target_col_name:
        target_col_letter = col[0].column_letter
        break
wb.close()

# 拼接读取的列范围,和你原有写法逻辑一致
usecols = f'B,{target_col_letter}'
df = pd.read_excel(
    file_location,
    index_col=None,
    na_values=['NA'],
    usecols=usecols
)
# 可选操作:给无列名的B列设置列名
df.columns = ['fixed_b_col', target_col_name]

注意事项

  • 你原有代码的文件路径缺少开头的单引号,且未加转义标识,运行会报错,参考示例中的写法修改即可
  • 方案2需要提前安装openpyxl依赖:pip install openpyxl
  • 两种方案都适配目标列位置每月变动的场景,不需要手动修改列号配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:15:03