Fix: ‘numpy.ndarray’ object has no attribute ‘index’ ???

This error occurs when a numpy ndarray object is used where a pandas DataFrame object is expected. The numpy ndarray object does not have the index attribute that the pandas DataFrame object has. To fix this, the numpy ndarray must be converted into a pandas DataFrame so that the index attribute can be accessed.


One error you may encounter when using NumPy is:

AttributeError: 'numpy.ndarray' object has no attribute 'index'

This error occurs when you attempt to use the index() function on a NumPy array, which does not have an index attribute available to use.

The following example shows how to address this error in practice.

How to Reproduce the Error

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
x = np.array([4, 7, 3, 1, 5, 9, 9, 15, 9, 18])

We can use the following syntax to find the minimum and maximum values in the array:

#find minimum and maximum values of array
min_val = np.min(x)
max_val = np.max(x)

#print minimum and maximum values
print(min_val, max_val)

1 18

Now suppose we attempt to find the index position of the minimum and maximum values in the array:

#attempt to print index position of minimum value
x.index(min_val)

AttributeError: 'numpy.ndarray' object has no attribute 'index'

We receive an error because we can’t apply an index() function to a NumPy array.

How to Address the Error

To find the index position of the minimum and maximum values in the NumPy array, we can use the NumPy where() function:

#find index position of minimum value
np.where(x == min_val)

(array([3]),)

#find index position of maximum value
np.where(x == max_val)

(array([9]),)

From the output we can see:

  • The minimum value in the array is located in index position 3.
  • The maximum value in the array is located in index position 9.

For example, we can use the following syntax to find which index positions are equal to the value 9 in the NumPy array:

#find index positions that are equal to the value 9
np.where(x == 9)

(array([5, 6, 8]),)

From the output we can see that the values in index positions 5, 6, and 8 are all equal to 9.

The following tutorials explain how to fix other common errors in Python:

x