![]() |
VOOZH | about |
In NumPy, you can access or modify array elements at specific indices. The numpy.put() function allows you to insert values into an array at designated positions, supporting all array dimensions (1-D, 2-D, 3-D). It also provides modes to handle out-of-bound indices.
The put() function updates an existing array by placing values at specified indices. It is commonly used to modify arrays without creating new ones.
numpy.put(arr, indices, values, mode='raise')
Parameters:
Return value: Returns None and modifies the original array in-place.
Example 1: Replace specific positions in a 1-D array with values from another array.
[ 1 10 22 30 15]
Explanation:
Example 2: Insert values from a 1-D array into specific flattened positions of a 2-D array.
[[ 1 10 22 15] [ 14 58 6 100]]
Explanation:
Example 3: Insert values from a 2-D array into specific positions of a 3-D array.
[[[ 1 25 15] [30 10 55] [20 45 6]] [[50 40 8] [70 85 50] [11 22 33]] [[19 69 36] [ 1 5 24] [ 4 20 9]]]
Explanation:
Example 4: Demonstrate behavior when indices are out-of-bounds using mode 'raise'.
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
IndexError: index 15 is out of bounds for axis 0 with size 6
Explanation:mode='raise' ensures an error occurs if an index exceeds the array size.
Example 5: Handle out-of-bound indices by clipping them to the array boundary.
[[ 1 10 22] [14 58 15]]
Explanation: