VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-get-values-of-an-numpy-array-at-certain-index-positions/

⇱ How to Get Values of an NumPy Array at Certain Index Positions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Get Values of an NumPy Array at Certain Index Positions

Last Updated : 27 Sep, 2025

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.

numpy.put() function

The put() function updates an existing array by placing values at specified indices. It is commonly used to modify arrays without creating new ones.

Syntax:

numpy.put(arr, indices, values, mode='raise')

Parameters:

  • arr: Target NumPy array to modify.
  • indices: List/array of integer positions where values are to be placed.
  • values: Values to insert at the specified indices. Can be scalar or array.
  • mode (optional): How to handle out-of-bounds indices 'raise' - Raise an error (default), 'wrap' - Wrap around to the beginning and 'clip' - Clip indices to the array boundary.

Return value: Returns None and modifies the original array in-place.

Examples

Example 1: Replace specific positions in a 1-D array with values from another array.


Output
[ 1 10 22 30 15]

Explanation:

  • a1.put([0, 4], a2) places 1 at index 0 and 15 at index 4.
  • Original array a1 is updated in-place.

Example 2: Insert values from a 1-D array into specific flattened positions of a 2-D array.


Output
[[ 1 10 22 15]
 [ 14 58 6 100]]

Explanation:

  • put() flattens a1 internally, placing values at positions [0, 3, 6].
  • Values [1, 15, 6] replace original elements at these positions.
  • The 2-D structure remains unchanged when printed. 

Example 3: Insert values from a 2-D array into specific positions of a 3-D array.


Output
[[[ 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:

  • Flattened indices [0, 2, 4, 8, 10, 14] are replaced by values from a2.
  • put() automatically reshapes the flattened data back to the 3-D structure.

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.


Output
[[ 1 10 22]
 [14 58 15]]

Explanation:

  • Out-of-bound index 15 is clipped to the last element.
  • Values [1, 15] are inserted at indices 0 and last position.
Comment
Article Tags: