TypeError: expected sequence, got ndarray

Loading

The error “TypeError: expected sequence, got ndarray” occurs when a function expects a list, tuple, or other sequence-like data structure but receives a NumPy ndarray.

Possible Causes and Fixes:

1. Using NumPy Array Instead of List

Some functions in Python, especially those expecting iterable sequences, may not work directly with NumPy arrays.

Incorrect:

import numpy as np

arr = np.array([1, 2, 3])
print(sum(arr)) # TypeError

Fix: Convert the ndarray to a list before using the function.

print(sum(arr.tolist()))

2. Passing NumPy Array to a Function Expecting a Sequence

Certain machine learning libraries, such as Scikit-learn, expect a sequence (list) rather than an ndarray.

Incorrect:

from sklearn.preprocessing import MinMaxScaler
import numpy as np

scaler = MinMaxScaler()
X = np.array([1, 2, 3, 4, 5])
X_scaled = scaler.fit_transform(X) # TypeError

Fix: Reshape the array to 2D.

X_scaled = scaler.fit_transform(X.reshape(-1, 1))

3. Providing a NumPy Array Instead of a List to a Pandas DataFrame

Pandas expects sequences like lists when creating a DataFrame.

Incorrect:

import pandas as pd

data = np.array([1, 2, 3])
df = pd.DataFrame(data, columns="A") # TypeError

Fix:

df = pd.DataFrame(data, columns=["A"])

4. Using NumPy Array Instead of List in zip()

The zip() function expects iterable sequences, not ndarray.

Incorrect:

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

zipped = zip(arr1, arr2) # TypeError

Fix: Convert to lists.

zipped = zip(arr1.tolist(), arr2.tolist())

Leave a Reply

Your email address will not be published. Required fields are marked *