Python NumPy: How to Resolve "'numpy.ndarray' object has no attribute 'index'"
When working with NumPy arrays, you might try to find the position of an element using the .index() method - the same way you would with a Python list. However, NumPy arrays don't have an index() method, and attempting to use it raises AttributeError: 'numpy.ndarray' object has no attribute 'index'.
In this guide, we'll explain why this happens and show you multiple alternatives for finding element positions in NumPy arrays.
Why Does This Error Occur?
Python lists have a built-in .index() method that returns the position of the first occurrence of a value:
my_list = [10, 20, 30, 40]
print(my_list.index(30)) # Output: 2
NumPy arrays, however, are a different data type (numpy.ndarray) with their own set of methods - and .index() is not one of them.
❌ Wrong - Using .index() on a NumPy array:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr.index(30))
Output:
AttributeError: 'numpy.ndarray' object has no attribute 'index'
Solutions
Solution 1: Use np.where() (Recommended)
np.where() is the most common and versatile replacement. It returns the indices of all elements that match a condition:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
indices = np.where(arr == 30)
print(indices)
Output:
(array([2]),)
To get just the index as an integer:
index = np.where(arr == 30)[0][0]
print(index)
Output:
2
When the Element Appears Multiple Times
np.where() returns all matching indices, making it more powerful than list's .index() (which only returns the first):
import numpy as np
arr = np.array([5, 10, 5, 20, 5, 30])
indices = np.where(arr == 5)
print(indices)
Output:
(array([0, 2, 4]),)
When the Element Doesn't Exist
If the element is not found, np.where() returns an empty array - it doesn't raise an error:
import numpy as np
arr = np.array([10, 20, 30])
indices = np.where(arr == 99)
print(indices)
print(f"Found: {len(indices[0]) > 0}")
Output:
(array([], dtype=int64),)
Found: False
This is safer than Python's list.index(), which raises a ValueError if the element isn't found. With np.where(), you can simply check if the result is empty.
Solution 2: Use np.argwhere() for Cleaner Output
np.argwhere() returns the indices in a more readable array format, which is especially useful for multi-dimensional arrays:
import numpy as np
arr = np.array([10, 20, 30, 20, 40])
indices = np.argwhere(arr == 20)
print(indices)
Output:
[[1]
[3]]
For a 2D array:
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
indices = np.argwhere(matrix == 5)
print(indices) # Row 1, Column 1
Output:
[[1 1]]
Solution 3: Use np.searchsorted() for Sorted Arrays
If your array is sorted, np.searchsorted() is the fastest option - it uses binary search (O(log n) instead of O(n)):
import numpy as np
arr = np.array([10, 20, 30, 40, 50]) # Must be sorted
index = np.searchsorted(arr, 30)
print(index)
Output:
2
np.searchsorted() returns the position where the value would be inserted to maintain sorted order. If the value doesn't exist in the array, it still returns an index. Always verify the value actually exists at that position:
import numpy as np
arr = np.array([10, 20, 40, 50])
index = np.searchsorted(arr, 30)
print(index) # 2 but arr[2] is 40, not 30!
# Verify the element exists
if index < len(arr) and arr[index] == 30:
print(f"Found at index {index}")
else:
print("Element not found")
Solution 4: Convert to a List (Simple but Less Efficient)
If you only need to find a single element and performance isn't critical, convert the array to a list and use .index():
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
index = arr.tolist().index(30)
print(index)
Output:
2
This approach:
- Creates a full copy of the array as a Python list - slow and memory-intensive for large arrays.
- Raises a
ValueErrorif the element isn't found (unlikenp.where()). - Only returns the first occurrence (unlike
np.where()which returns all).
Use this only for quick scripts or small arrays.
Solution 5: Use np.nonzero() with a Condition
np.nonzero() returns indices of elements that are non-zero. Combined with a boolean condition, it works like np.where():
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
indices = np.nonzero(arr == 30)
print(indices)
Output:
(array([2]),)
Practical Examples
Finding the Index of the Maximum or Minimum Value
import numpy as np
scores = np.array([85, 92, 78, 95, 88])
max_index = np.argmax(scores)
min_index = np.argmin(scores)
print(f"Highest score: {scores[max_index]} at index {max_index}")
print(f"Lowest score: {scores[min_index]} at index {min_index}")
Output:
Highest score: 95 at index 3
Lowest score: 78 at index 2
Finding Indices Where a Condition Is Met
import numpy as np
temperatures = np.array([72, 85, 90, 68, 95, 88, 70])
# Find indices where temperature exceeds 85
hot_days = np.where(temperatures > 85)[0]
print(f"Hot day indices: {hot_days}")
print(f"Hot day temperatures: {temperatures[hot_days]}")
Output:
Hot day indices: [2 4 5]
Hot day temperatures: [90 95 88]
Safe Index Lookup with a Fallback
import numpy as np
def find_index(arr, value, default=-1):
"""Find the first index of a value in a NumPy array."""
indices = np.where(arr == value)[0]
if len(indices) > 0:
return indices[0]
return default
arr = np.array([10, 20, 30, 40])
print(find_index(arr, 30)) # 2
print(find_index(arr, 99)) # -1 (not found)
Output:
2
-1
Method Comparison
| Method | Returns | Multiple Matches | Element Not Found | Performance | Best For |
|---|---|---|---|---|---|
np.where() | Tuple of arrays | ✅ All indices | Empty array | O(n) | General use |
np.argwhere() | 2D array of indices | ✅ All indices | Empty array | O(n) | Multi-dimensional arrays |
np.searchsorted() | Single index | ❌ First only | Insertion point | O(log n) | Sorted arrays |
.tolist().index() | Single integer | ❌ First only | Raises ValueError | O(n) + copy | Quick scripts |
np.argmax() / np.argmin() | Single index | ❌ First only | N/A | O(n) | Finding max/min position |
Conclusion
The AttributeError: 'numpy.ndarray' object has no attribute 'index' error occurs because NumPy arrays don't have a .index() method like Python lists do.
- The recommended replacement is
np.where(arr == value), which returns all matching indices and safely returns an empty array if the element isn't found. - For sorted arrays,
np.searchsorted()provides faster performance.
Avoid converting to a list with .tolist().index() for large arrays, as it's both slower and less flexible than NumPy's native solutions.