ValueError: Expected 2D array, got 1D array instead" in sklearnScikit-learn expects a (n_samples, n_features) matrix. A flat 1D array, the shape you get by default from a single NumPy column or a .values call on one DataFrame column, doesn't qualify, even when there's obviously only one feature. This article reproduces the error for a linear model and a scaler, walks through the reshape(-1, 1) fix, and covers the pandas-specific version of the same error, which needs a different fix entirely.
A single-feature NumPy array built the obvious way, without an explicit column dimension, triggers this immediately on fit():
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
LinearRegression().fit(X, y)
# ValueError: Expected 2D array, got 1D array instead:
# array=[1 2 3 4 5].
# Reshape your data either using array.reshape(-1, 1) if your data has
# a single feature or array.reshape(1, -1) if it contains a single sample.
The error message names the fix directly. Read it carefully before pasting the suggested call, though: it offers two different reshape targets, and only one applies here.
X.shape here is (5,), a 1D array of 5 numbers with no second axis at all. Scikit-learn needs (5, 1), five samples of one feature each, which is a different shape even though both represent the same five numbers.
Adding an explicit feature axis resolves it:
X_reshaped = X.reshape(-1, 1)
print(X_reshaped.shape)
# (5, 1)
model = LinearRegression().fit(X_reshaped, y)
print(model.coef_, model.intercept_)
# [2.] 0.0
The -1 tells NumPy to infer that dimension's size from the array's length. Only the second argument, the feature count, has to be fixed at 1, so this same call works regardless of how many samples X holds. reshape(1, -1), the other option the error mentions, handles a different shape mismatch: one sample with several features. That case gets its own reshape call, but the mechanics are the same.
A successful fit() call says nothing about how the next input will be shaped. Pass a single new value to predict() the way you'd type it, and the same model that just trained fine throws the identical error:
model.predict(np.array([6]))
# ValueError: Expected 2D array, got 1D array instead:
# array=[6].
# Reshape your data either using array.reshape(-1, 1) ...
model.predict(np.array([6]).reshape(-1, 1))
# array([12.]) -- works
predict() weeks later, often in a completely different file or service. A green training run says nothing about whether that later call site reshapes its input.
Pulling a single column out of a DataFrame with single brackets produces a pandas Series, which triggers a related but distinctly worded version of the same underlying problem:
import pandas as pd
df = pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y': [2, 4, 6, 8, 10]})
LinearRegression().fit(df['x'], df['y'])
# ValueError: Expected a 2-dimensional container but got instead.
# Pass a DataFrame containing a single row (i.e. single sample) or a single
# column (i.e. single feature) instead.
Scikit-learn recognizes the pandas type here and phrases the message accordingly, though the underlying cause is the same missing dimension. The fix looks different, though: swap the single brackets for double ones and select the column as a one-column DataFrame instead of reaching for .reshape(), which a Series doesn't take well to.
df[['x']].shape # (5, 1) -- a DataFrame, 2D
df['x'].shape # (5,) -- a Series, 1D
model = LinearRegression().fit(df[['x']], df['y'])
print(model.coef_)
# [2.]
In a notebook, df['x'] and df[['x']] print out almost identically and hold the exact same values. That similarity is exactly what makes this version of the bug easy to miss on a quick read: the whole difference lives in a bracket count, easy to glance past.
The 2D requirement runs through every scikit-learn transformer, predictive models included. StandardScaler raises the identical error on the identical shape of input:
from sklearn.preprocessing import StandardScaler
X = np.array([1, 2, 3, 4, 5])
scaler = StandardScaler()
scaler.fit(X)
# ValueError: Expected 2D array, got 1D array instead: array=[1. 2. 3. 4. 5.].
# Reshape your data either using array.reshape(-1, 1) ...
scaler.fit(X.reshape(-1, 1))
print(scaler.mean_)
# [3.]
A scaling or encoding step is often the very first line of a preprocessing pipeline, before any model gets involved. That means this error can show up before you've reached the part of the code you actually meant to debug.
Input type Fix
──────────────────────────────────────── ─────────────────────────────────────────
1D NumPy array, one feature, many samples array.reshape(-1, 1)
1D NumPy array, one sample, many features array.reshape(1, -1)
A single scalar value at predict() time np.array([[value]]) or [[value]]
pandas Series from df['col'] df[['col']] (double brackets, no reshape)
Any transformer (scaler, encoder, PCA...) same reshape rules, same fix