In this article, we will see some of the possible reasons for the error “object has no attribute columns“.
The error “‘numpy.ndarray’ object has no attribute ‘columns'” usually occurs when trying to access the ‘columns‘ attribute of a NumPy ndarray. The ‘columns‘ attribute is not a built-in attribute of NumPy ndarrays, and using it leads to an error.
Most common cause of this issue is getting confused between numpy arrays and pandas dataframes. This is specific to the pandas dataframe and is not available in the NumPy. When you try to use it on numPy, you will get an error.
Following is the way how you can resolve this error.
Convert the numPy array to dataframe
Suppose we have a NumPy ndarray called ‘arr‘ and want to get the column labels. Instead of usingarr.columns
, which raises the attribute error, convert the ndarray to a Pandas DataFrame and access the columns using the ‘columns’ attribute.
import numpy as np
import pandas as pd
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # NumPy ndarray
# Convert ndarray to Pandas DataFrame
df = pd.DataFrame(arr, columns=['A', 'B', 'C'])
# Access column labels
print(df.columns)
By converting the NumPy ndarray to a Pandas DataFrame, we can access the column labels using the ‘columns‘ attribute without encountering the attribute error.