Numpy.put() Method

Numpy.put() method is “used to replace specific elements of an array with given values of p_array.” Array indexed works on a flattened array.

Syntax

numpy.put(array, indices, values, mode)

Parameters

The NumPy put() function can take up to 4 parameters.

  1. array: It is the array in which we want to work
  2. indices: Index of the values to be replaced. When the function is called, it flattens and works on the array.
  3. values: It’s an array that contains the values to be inserted in the array.
  4. mode: This is an optional field. We have 3 types of modes:
    1. raise: This is the default mode that raises an error.
    2. warp: It warps around the array.
    3. clip: It clips to the range of the array.

Return Value

The put() function returns a modified array after replacing the values.

Example 1: How to Use np.put() Method

# Importing numpy
import numpy as np

# We will create an 1D array
arr = np.array([47, 20, 41, 63, 21, 4, 74])

# Printing the array
print("The array is: ", arr)

# Shape of the array
print("Shape of the array is : ", np.shape(arr))

# Now we will replace array elements at position 2 and 3
np.put(arr, [2, 3], [100, 1000])

# Printing new array
print("New array is: ", arr)

Output

The array is: [47 20 41 63 21 4 74]
Shape of the array is : (7,)
New array is: [47 20 100 1000 21 4 74]

Example 2: Replace array elements at position 2 and 3

# Importing numpy
import numpy as np

# We will create an 1D array
arr = np.array([47, 20, 41, 63, 21, 4, 74])

# Printing the array
print("The array is: ", arr)

# Shape of the array
print("Shape of the array is : ", np.shape(arr))

# Now we will replace array elements at position 2 and 3
np.put(arr, [2, 100], [90, 540], mode='warp')

# Printing new array
print("New array is: ", arr)

Output

The array is: [47 20 41 63 21 4 74]
Shape of the array is : (7,)
New array is: [ 47 20 540 63 21 4 74]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.