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

如何用Pandas索引Excel未知列名的首列(多工作表场景)

如何在未知首列标题时用Pandas索引该列并将多工作表Excel转JSON

核心问题:索引未知标题的首列

你已经通过index_1 = data.columns[0]拿到了首列的标题,在Python里直接用列名索引就能获取整列:

chipset = data[index_1]
print(chipset)

如果不想先获取列名,也可以直接用位置索引iloc,首列是第0列,写法更简洁:

chipset = data.iloc[:, 0]  # :表示所有行,0表示第0列
print(chipset)

完整解决方案:多工作表转JSON(首列作为索引)

结合你的需求,这里给出遍历所有工作表、将每个表的首列作为JSON索引的完整代码:

import pandas as pd
import json

datapath = 'myfile.xlsx'

# 读取Excel中所有工作表,返回{表名: DataFrame}的字典
all_worksheets = pd.read_excel(datapath, sheet_name=None)

# 存储每个工作表的JSON结果
final_json = {}

for sheet_name, df in all_worksheets.items():
    # 获取首列标题
    first_col_name = df.columns[0]
    # 将首列设为DataFrame索引,再转成指定格式的JSON
    # orient='index'会生成 {首列数据: {其他列标题: 对应值}, ...} 的结构
    sheet_json_data = df.set_index(first_col_name).to_json(orient='index', force_ascii=False)
    # 把当前工作表的JSON结果存入最终字典
    final_json[sheet_name] = json.loads(sheet_json_data)  # 转成Python字典方便后续处理

# 将最终结果写入JSON文件
with open('excel_to_json_result.json', 'w', encoding='utf-8') as f:
    json.dump(final_json, f, ensure_ascii=False, indent=2)

关键说明

  • sheet_name=None:Pandas会读取Excel中的所有工作表,返回一个以表名为键、对应DataFrame为值的字典。
  • set_index(first_col_name):把首列设置为DataFrame的索引,这样转JSON时首列数据会成为JSON的顶层键。
  • to_json(orient='index'):控制JSON的输出结构,orient参数还有'records'、'columns'等选项,可根据需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:25:21