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

设置DataFrame列名时出现ValueError长度不匹配问题排查

Pandas设置UCI汽车数据集列名时的ValueError解决办法

错误原因

触发的ValueError: Length mismatch: Expected axis has 26 elements, new values have 25 elements,核心问题是定义headers列表时,"hosepower"与"peak-rpm"之间缺失逗号。Python会自动拼接相邻的字符串字面量,导致这两个本该独立的列名被合并成一个元素,最终列名列表仅25个元素,与数据集的26列数量不匹配。

修正后的代码

补全缺失的逗号即可解决问题:

import pandas as pd

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data'

df = pd.read_csv(url, header=None)

# 修正:在"hosepower"和"peak-rpm"之间添加逗号
headers = ["symboling","normalized-losses","make","fuel-type","aspiration","num-of-doors","body-style","drive-wheels","engine-location","wheel-base","length","width","height","curb-weight","engine-type","num-of-cylinders","engine-size","fuel-system","bore","stroke","compresstion-ratio","hosepower","peak-rpm","city=mpg","highway-mpg","price"]

df.columns = headers
df.head(5)
df.dtypes
df.describe()

防错小技巧

为避免同类低级错误,可在设置列名前先验证列数是否匹配:

print(f"数据集列数: {df.shape[1]}")
print(f"列名列表长度: {len(headers)}")

若两者数值不一致,直接定位列名列表的问题即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:50:54