Resolved: Attribute Error: ‘numpy.ndarray’ Object has no Attribute ‘index’
Therefore, you may be tempted to use the index() method provided in a Python list to get the index of an element.
Let us take an example:
We have a Python list containing four-string elements in the above example. To find the index of an element in the list, we use the index() function and pass the value we are looking for as the parameter.
If the element is found, the function should return the element index in the list. An example output is as shown:
What happens when we attempt to perform the same operation on a NumPy array?
If we run the code above, it will return an error as shown below:
The attribute error occurs when we call an attribute or method not defined for the object.
Since the index() method is only defined in a Python list and not a NumPy array, the code above will result in an attribute error.
If you want to get the index of an element from a NumPy array, you can use the where function.
The function syntax is as shown below:
We can adopt the function above to get the index of an element as shown below:
The function should return a tuple with the element’s index in the array.
This article discussed the attribute error in Python, why it occurs, and how to resolve it in a NumPy array.
Thanks for reading!!