Python
OneHotEncoder
2D array
data preprocessing
machine learning error

Error Expected 2D array, got 1D array instead Using OneHotEncoder

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

The Expected 2D array, got 1D array instead error appears often when using scikit-learn preprocessing tools such as OneHotEncoder. It happens because scikit-learn treats feature data as a matrix, even when you only have one categorical column.

Once you understand the shape rule, the fix is straightforward. The encoder expects X to look like a table with rows and columns, not like a flat list of values.

Why OneHotEncoder Requires Two Dimensions

Scikit-learn follows a consistent convention:

  • 'X is a two-dimensional feature matrix with shape (n_samples, n_features)'
  • 'y is usually a one-dimensional target vector with shape (n_samples,)'

If you pass a single feature column as a flat NumPy array such as ["red", "blue", "green"], that array has shape (3,). To the encoder, that is missing the feature axis. It cannot tell whether those values represent three samples of one feature or one sample with three features.

OneHotEncoder therefore raises an error instead of guessing.

Fixing the Shape

For a single categorical feature, reshape the array so that each sample occupies one row and the single feature occupies one column. In NumPy, that usually means reshape(-1, 1).

python
1import numpy as np
2from sklearn.preprocessing import OneHotEncoder
3
4colors = np.array(["red", "blue", "green", "red"])
5
6encoder = OneHotEncoder(sparse_output=False)
7encoded = encoder.fit_transform(colors.reshape(-1, 1))
8
9print(encoded)
10print(encoder.categories_)

The important part is reshape(-1, 1). The -1 tells NumPy to infer the number of rows from the data length, and 1 declares that there is exactly one feature column.

If you print colors.shape before reshaping, you get (4,). After reshaping, you get (4, 1), which is what the encoder expects.

Working with Pandas DataFrames

This issue also appears in pandas when selecting a column. These two statements look similar but return different shapes:

python
1import pandas as pd
2from sklearn.preprocessing import OneHotEncoder
3
4df = pd.DataFrame(
5    {
6        "color": ["red", "blue", "green", "red"],
7        "price": [10, 12, 9, 11],
8    }
9)
10
11encoder = OneHotEncoder(sparse_output=False)
12
13one_dimensional = df["color"]     # Series
14two_dimensional = df[["color"]]   # DataFrame
15
16encoded = encoder.fit_transform(two_dimensional)
17print(encoded)

df["color"] returns a Series, which behaves like a one-dimensional object. df[["color"]] returns a DataFrame, which preserves the two-dimensional shape. When you are encoding a single column from pandas, the double brackets are usually the cleanest solution.

Using OneHotEncoder in a Pipeline

In real projects, you rarely call OneHotEncoder in isolation. It is usually part of a preprocessing pipeline that handles both categorical and numeric columns.

python
1import pandas as pd
2from sklearn.compose import ColumnTransformer
3from sklearn.pipeline import Pipeline
4from sklearn.preprocessing import OneHotEncoder, StandardScaler
5from sklearn.linear_model import LogisticRegression
6
7df = pd.DataFrame(
8    {
9        "color": ["red", "blue", "green", "red"],
10        "weight": [1.2, 0.8, 1.5, 1.1],
11        "label": [1, 0, 1, 0],
12    }
13)
14
15X = df[["color", "weight"]]
16y = df["label"]
17
18preprocessor = ColumnTransformer(
19    transformers=[
20        ("cat", OneHotEncoder(handle_unknown="ignore"), ["color"]),
21        ("num", StandardScaler(), ["weight"]),
22    ]
23)
24
25model = Pipeline(
26    steps=[
27        ("preprocess", preprocessor),
28        ("classifier", LogisticRegression()),
29    ]
30)
31
32model.fit(X, y)
33print(model.predict(X))

This avoids manual reshaping in application code because the DataFrame keeps the feature matrix structure intact.

What the Error Is Really Telling You

The message is not specific to OneHotEncoder. Many scikit-learn transformers and estimators will raise the same exception because they all expect the same input contract for X.

That means the durable lesson is not just "use reshape." The real lesson is to check your array shape whenever you move between plain Python lists, NumPy arrays, and pandas objects.

Useful debugging checks include:

python
print(type(colors))
print(colors.shape)

Those two lines usually reveal the problem immediately.

Common Pitfalls

One common mistake is reshaping the target vector y instead of the feature column X. OneHotEncoder should transform input features, not the labels unless you are solving a very specific preprocessing problem.

Another issue is forgetting that newer scikit-learn versions use sparse_output instead of the older sparse argument. If sample code from an older article fails, check the installed version before copying parameters.

It is also easy to encode the same column twice: once manually and once again inside a ColumnTransformer. That leads to duplicated features and confusing model behavior.

Finally, if production data may contain unseen categories, set handle_unknown="ignore" so inference does not fail on new values.

Summary

  • 'OneHotEncoder expects feature input with shape (n_samples, n_features).'
  • A flat array such as shape (n_samples,) is treated as invalid for feature data.
  • Use reshape(-1, 1) for a single NumPy column, or use df[["column"]] in pandas.
  • Pipelines and ColumnTransformer make shape handling much safer in real applications.
  • When debugging scikit-learn preprocessing, inspect both the object type and the array shape.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.