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.
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:
- '
Xis a two-dimensional feature matrix with shape(n_samples, n_features)' - '
yis 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).
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:
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.
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:
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
- '
OneHotEncoderexpects 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 usedf[["column"]]in pandas. - Pipelines and
ColumnTransformermake shape handling much safer in real applications. - When debugging scikit-learn preprocessing, inspect both the object type and the array shape.
Related reading
- Error Failed to load the native TensorFlow runtime
- Error from tensorflow.examples.tutorials.mnist import input_data
- Error importing BERT module 'tensorflow._api.v2.train' has no attribute 'Optimizer
- Error importing tensorflow AlreadyExistsError Another metric with the same name already exists.
- Error Import Error No module named numpy on Windows
- Error in Confusion Matrix the data and reference factors must have the same number of levels
- Error in Python script Expected 2D array, got 1D array instead?
- ErrorCannot fit requested classes in a single dex file.Try supplying a main-dex list. methods 72477 65536

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 courseTrack 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.