0
0
NumPydata~5 mins

np.take() and np.put() for advanced selection in NumPy

Choose your learning style9 modes available
Introduction

These functions help you pick or change specific parts of data in arrays easily.

You want to select elements from an array using a list of positions.
You need to replace certain elements in an array at specific positions.
You want to reorder data based on index positions.
You want to update values in an array without looping manually.
Syntax
NumPy
np.take(array, indices, axis=None, mode='raise')
np.put(array, indices, values, mode='raise')

np.take() selects elements from array at indices.

np.put() replaces elements in array at indices with values.

Examples
Selects elements at positions 1 and 3 from the array.
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
selected = np.take(arr, [1, 3])
print(selected)
Replaces elements at positions 0 and 2 with 100 and 300.
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
np.put(arr, [0, 2], [100, 300])
print(arr)
Selects rows 0 and 2 from a 2D array.
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
selected = np.take(arr, [0, 2], axis=0)
print(selected)
Replaces elements at flattened positions 1 and 4 with 20 and 40.
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
np.put(arr, [1, 4], [20, 40])
print(arr)
Sample Program

This program shows how to pick specific elements from an array and then change some elements by their positions.

NumPy
import numpy as np

# Create a 1D array
arr = np.array([5, 10, 15, 20, 25])

# Use np.take to select elements at positions 0, 2, 4
selected = np.take(arr, [0, 2, 4])
print('Selected elements:', selected)

# Use np.put to replace elements at positions 1 and 3
np.put(arr, [1, 3], [100, 200])
print('Array after put:', arr)
OutputSuccess
Important Notes

Indices in np.put() refer to the flattened array if the array is multi-dimensional.

Use the axis parameter in np.take() to select along a specific dimension.

Both functions support a mode parameter to control behavior when indices are out of bounds.

Summary

np.take() picks elements by index from arrays.

np.put() changes elements at given positions.

They help work with array data without loops.