When working with the numpy module we might encounter several errors and in this article, we will see how to resolve the most common error which we see when working with NumPy ndarray object i.e. “‘numpy ndarray’ object has no attribute ‘columns’“.

Let us know first understand in which cases you might get this error. Following are the different scenarios where we might see the above error.

Confusion between Pandas Dataframe and NumPy ndarray

Sometimes we get confused and assume that NumPy ndarray has the same attributes as Pandas DataFrame. Make sure you are using the NumPy and not the Pandas DataFrames. In NumPy, we don’t have a columns attribute.

The following example shows you the difference in accessing the columns attribute using the pandas dataframe & numpy ndarray.

In the below example, we are trying to access the ‘columns‘ attribute on the NumPy ndarray arr which will result in the “‘numpy ndarray’ object has no attribute ‘columns‘” error.

import numpy as np
import pandas as pd

# Create a NumPy ndarray
arr = np.array([[1, 2, 3], [4, 5, 6]])

# Accessing 'columns' attribute on NumPy ndarray (error)
print(arr.columns)

The following example shows how to use the columns attribute with the Pandas DataFrame without any errors.

# Create a Pandas DataFrame
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]])

# Accessing 'columns' attribute on Pandas DataFrame (success)
print(df.columns)

Categorized in:

Tagged in: