NumPy ndarray.put()

The numpy.ndarray.put() method modifies an array by placing specified values at given indices. It operates in-place and can handle different index modes to control out-of-bounds behavior.

Syntax

</>
Copy
ndarray.put(indices, values, mode='raise')

Parameters

ParameterTypeDescription
indicesarray_likeTarget indices where values will be placed. Can be a single integer or an array of indices.
valuesarray_likeValues to be placed at the specified indices. If fewer values than indices are provided, they will be repeated.
mode{‘raise’, ‘wrap’, ‘clip’}, optionalDetermines out-of-bounds handling.
  • 'raise' (default): Raises an error for out-of-bounds indices.
  • 'wrap': Wraps indices cyclically.
  • 'clip': Clips indices to valid range.

Return Value

Modifies the array in-place and does not return any value.


Examples

1. Replacing Specific Elements in an Array

In this example, we replace elements at specific indices with new values.

</>
Copy
import numpy as np

# Create an array
arr = np.array([10, 20, 30, 40, 50])

# Define indices where values should be placed
indices = [1, 3]

# Define values to be placed at the specified indices
values = [99, 77]

# Modify the array in-place
arr.put(indices, values)

# Print the modified array
print(arr)  # Output: [10 99 30 77 50]

Output:

[10 99 30 77 50]

The values at indices 1 and 3 are replaced with 99 and 77, respectively.

2. Handling Fewer Values than Indices

When fewer values than indices are provided, they are repeated cyclically.

</>
Copy
import numpy as np

arr = np.array([5, 10, 15, 20, 25, 30])

indices = [0, 2, 4]
values = [100]  # Only one value provided

arr.put(indices, values)

print(arr)  # Output: [100  10 100  20 100  30]

Output:

[100  10 100  20 100  30]

The single value 100 is reused for all specified indices.

3. Using mode='wrap' to Handle Out-of-Bounds Indices

The 'wrap' mode cycles indices back within valid range.

</>
Copy
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

indices = [6, 7, 8]  # Out-of-bounds indices
values = [50, 60, 70]

arr.put(indices, values, mode='wrap')

print(arr)

Output:

[ 1 50 60 70  5]

The indices wrap cyclically (e.g., 6 maps to 1, 7 maps to 2, and 8 maps to 3).

4. Using mode='clip' to Prevent Out-of-Bounds Errors

The 'clip' mode restricts indices to valid bounds.

</>
Copy
import numpy as np

arr = np.array([5, 10, 15, 20, 25])

indices = [-3, 6, 8]  # Some out-of-bounds indices
values = [99, 88, 77]

arr.put(indices, values, mode='clip')

print(arr)

Output:

[99 10 15 20 77]