Therefore, you may be tempted to use the index() method provided in a Python list to get the index of an element.
Error
Let us take an example:
print(f"index: {my_list.index('MongoDB')}")
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?
import numpy as np
arr = np.array(['MySQL', 'PostgreSQL', 'MongoDB', 'Redis'])
print(f"index: {arr.index('MongoDB')}")
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.
Solution
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.
Conclusion
This article discussed the attribute error in Python, why it occurs, and how to resolve it in a NumPy array.
Thanks for reading!!
from https://ift.tt/9X5sxM0
0 Comments