When working with NumPy arrays, you frequently need to access values at specific positions or replace values at certain indices. NumPy provides several efficient ways to do this, from basic indexing to the np.put() function for in-place modifications. In this guide, we'll cover how to get values at specific indices and how to set values using various methods.
Getting Values at Specific Indices
Using Basic Indexing
The simplest way to access elements at specific positions:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[2])
indices = [0, 2, 4]
print(arr[indices])Output:
30
[10 30 50]Using np.take()
np.take() retrieves elements at specified indices and works with any array dimension:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
result = np.take(arr, [0, 2, 4])
print(result)Output:
[10 30 50]For 2D arrays, np.take() works on the flattened array by default or along a specific axis:
import numpy as np
arr = np.array([[10, 20, 30],
[40, 50, 60]])
print(np.take(arr, [0, 3, 5]))
print(np.take(arr, [0, 2], axis=1))Output:
[10 40 60]
[[10 30]
[40 60]]Using Boolean Indexing
Select elements based on a condition:
import numpy as np
arr = np.array([10, 25, 30, 45, 50])
result = arr[arr > 25]
print(result)
indices = np.where(arr > 25)[0]
print(f"Values: {arr[indices]}, at indices: {indices}")Output:
[30 45 50]
Values: [30 45 50], at indices: [2 3 4]Setting Values at Specific Indices
Using Direct Assignment
The most straightforward way to set values:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
arr[2] = 99
print(arr)
arr[[0, 4]] = [100, 500]
print(arr)Output:
[10 20 99 40 50]
[100 20 99 40 500]Using np.put() - In-Place Modification
np.put() modifies an array in place by placing values at specified index positions. It works on the flattened version of the array, making it useful for multidimensional arrays.
Syntax:
numpy.put(arr, indices, values, mode='raise')| Parameter | Description |
|---|---|
arr |
Target array to modify |
indices |
Positions where values should be placed |
values |
Values to insert (broadcasts if shorter than indices) |
mode |
How to handle out-of-bounds: 'raise', 'wrap', 'clip' |
1D Array Example
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
values = [100, 500]
np.put(arr, [0, 4], values)
print(arr)Output:
[100 20 30 40 500]2D Array Example
np.put() treats multidimensional arrays as flattened when determining positions:
import numpy as np
arr = np.array([[10, 20, 30],
[40, 50, 60]])
print(f"Original:\n{arr}\n")
np.put(arr, [0, 3, 5], [100, 400, 600])
print(f"After put:\n{arr}")Output:
Original:
[[10 20 30]
[40 50 60]]
After put:
[[100 20 30]
[400 50 600]]3D Array Example
import numpy as np
arr = np.array([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]])
print(f"Shape: {arr.shape}")
np.put(arr, [0, 3, 7], [10, 40, 80])
print(arr)Output:
Shape: (2, 2, 2)
[[[10 2]
[ 3 40]]
[[ 5 6]
[ 7 80]]]Value Broadcasting
If fewer values than indices are provided, values are recycled:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
np.put(arr, [0, 2, 4], 99)
print(arr)Output:
[99 2 99 4 99]import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
np.put(arr, [0, 1, 2, 3], [10, 20])
print(arr)Output:
[10 20 10 20 5 6]Handling Out-of-Bounds Indices
The mode parameter controls what happens when indices exceed the array size:
mode='raise' (Default) - Raises an Error
import numpy as np
arr = np.array([10, 20, 30])
try:
np.put(arr, [0, 10], [100, 200], mode='raise')
except IndexError as e:
print(f"Error: {e}")Output:
Error: index 10 is out of bounds for axis 0 with size 3mode='clip' - Clips to the Nearest Valid Index
Out-of-bounds indices are clipped to the first or last position:
import numpy as np
arr = np.array([10, 20, 30])
np.put(arr, [0, 10], [100, 200], mode='clip')
print(arr) # Index 10 clips to index 2 (last element)Output:
[100 20 200]mode='wrap' - Wraps Around to the Beginning
Out-of-bounds indices wrap around using modulo:
import numpy as np
arr = np.array([10, 20, 30])
np.put(arr, [0, 4], [100, 200], mode='wrap')
print(arr) # Index 4 wraps to 4 % 3 = index 1Output:
[100 200 30]Using np.put_along_axis() for Advanced Placement
For placing values along a specific axis without flattening:
import numpy as np
arr = np.array([[10, 20, 30],
[40, 50, 60]])
indices = np.array([[2], [0]])
values = np.array([[99], [88]])
np.put_along_axis(arr, indices, values, axis=1)
print(arr)Output:
[[10 20 99]
[88 50 60]]Comparison of Methods
| Method | Returns | Modifies Original | Works on Flattened | Best For |
|---|---|---|---|---|
arr[indices] |
New array | ❌ | ❌ | Getting values |
np.take(arr, indices) |
New array | ❌ | ✅ (default) | Getting values with axis control |
arr[indices] = values |
None | ✅ | ❌ | Simple assignment |
np.put(arr, indices, values) |
None | ✅ | ✅ | In-place with out-of-bounds handling |
np.put_along_axis() |
None | ✅ | ❌ | Axis-specific placement |
Conclusion
To get values at specific indices in a NumPy array, use direct indexing (arr[[0, 2, 4]]) for simplicity or np.take() for more control over axes.
To set values at specific positions, use direct assignment (arr[[0, 2]] = [10, 20]) for straightforward cases or np.put() when you need in-place modification with out-of-bounds handling via mode='raise', 'clip', or 'wrap'.
Remember that np.put() operates on the flattened array, so for multidimensional arrays, calculate your indices based on the flattened position.