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

创建波士顿房价预测DataFrame时报arrays must be of same length错原因

Why df=pd.DataFrame(boston) Throws ValueError: arrays must all be same length in Boston Housing Prediction

Hey there! Let's unpack exactly why you're running into this error when working on your Boston Housing Price prediction code.

The Root Cause

The Boston Housing dataset from scikit-learn (note: this dataset was removed in scikit-learn v1.2+ due to ethical concerns, but assuming you're using an older version) is returned as a Bunch object—a dictionary-like structure that holds multiple components with different shapes and lengths. When you pass the entire Bunch directly to pd.DataFrame(), pandas tries to treat every attribute of the Bunch as a column in the DataFrame, but these attributes don't have matching lengths:

  • boston.data: A 2D array with shape (number_of_samples, number_of_features) (for the classic dataset, that's 506 rows × 13 features)
  • boston.target: A 1D array with shape (number_of_samples,) (506 elements, representing the median home values)
  • boston.feature_names: A list of strings with length equal to the number of features (13 elements, the names of each input feature)

Since these components have wildly different lengths (13 vs 506), pandas can't align them into a single DataFrame, hence the arrays must all be same length error.

The Fix

Instead of passing the entire Bunch to pd.DataFrame(), you need to build the DataFrame properly by combining the feature data and target separately:

import pandas as pd
from sklearn.datasets import load_boston

# Load the dataset (only works in scikit-learn <1.2)
boston = load_boston()

# Create DataFrame from the feature data, using feature names as column headers
df = pd.DataFrame(boston.data, columns=boston.feature_names)

# Add the target values as a new column (typically named 'MEDV' for median value)
df['MEDV'] = boston.target

If you're using a newer version of scikit-learn, you can use the California Housing dataset as a replacement with fetch_california_housing(), and apply the same logic to construct your DataFrame.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:42:30