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

Polars读取Pandas DataFrame时如何保留字段名?

解决Polars读取数据时丢失字段名的问题

问题1:从Pandas DataFrame转Polars丢失列名

正常情况下pl.from_pandas()会完整保留Pandas DataFrame的列名,出现丢失大概率是Pandas读取Excel时就没正确识别表头。

先验证Pandas读取后的结果:

pd_df = pd.read_excel(excel_path)
print(pd_df.columns)  # 查看Pandas读出来的列名是否正确

如果Pandas的列名就不对,调整pd.read_excel()的参数:

  • 若表头不在第一行,指定header参数(索引从0开始):
    pd_df = pd.read_excel(excel_path, header=1)  # 假设表头在第2行
    df = pl.from_pandas(pd_df)
    
  • 若表头有合并单元格、空值等异常,手动指定列名:
    cols = ["DataMonth", "ZipCode", "Total_Claimed_Subscribers", "Total_Claimed_Devices",
            "Service_Support", "Device_Support", "Total_Support"]
    pd_df = pd.read_excel(excel_path, header=None, names=cols)
    df = pl.from_pandas(pd_df)
    

问题2:直接用Polars读Excel时首行仅显示列名

你设置的read_csv_options是给CSV读取器用的,不适用于Excel的表头处理,这是核心问题。

根据需求调整pl.read_excel()的参数:

  1. 如果Excel第一行就是表头,直接读取即可:
    df = pl.read_excel(excel_path)
    
  2. 如果想替换原有表头为自定义列名:
    • 先读取含原有表头的数据,再用rename替换:
      df = pl.read_excel(excel_path).rename({
          "原列名1": "DataMonth",
          "原列名2": "ZipCode",
          # 补充其他需要替换的列映射
      })
      
    • 或者跳过原有表头行,直接设置新列名(Polars的read_excel本身支持new_columns参数):
      df = pl.read_excel(
          excel_path,
          header=0,  # 跳过第1行的原有表头
          new_columns=["DataMonth", "ZipCode", "Total_Claimed_Subscribers", "Total_Claimed_Devices",
                       "Service_Support", "Device_Support", "Total_Support"]
      )
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:52:08