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

如何让pandas.read_csv的index_col解析日期时不区分大小写?

解决方案

pd.read_csv()的index_col参数只支持精确匹配列名,没法直接实现不区分大小写的匹配。你可以分两步处理:

  1. 先读取CSV文件,不指定索引列,同时开启日期解析:
df = pd.read_csv(csv, parse_dates=True)
  1. 找到列名中不区分大小写匹配"date"的列,将其设置为DataFrame的索引:
# 筛选出列名小写后等于"date"的列
date_col = next(col for col in df.columns if col.lower() == "date")
df.set_index(date_col, inplace=True)

补充说明

如果担心CSV中不存在匹配的列,可以加个异常处理避免报错:

try:
    date_col = next(col for col in df.columns if col.lower() == "date")
    df.set_index(date_col, inplace=True)
except StopIteration:
    print("未找到名为date(不区分大小写)的列")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:34:53