Skip to main content

Python NumPy: How to Get and Set Values of a NumPy Array at Certain Index Positions

When working with NumPy arrays, you frequently need to access values at specific positions or replace values at certain indices. NumPy provides several efficient ways to do this, from basic indexing to the np.put() function for in-place modifications. In this guide, we'll cover how to get values at specific indices and how to set values using various methods.

Getting Values at Specific Indices

Using Basic Indexing

The simplest way to access elements at specific positions:

import numpy as np

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

# Single index
print(arr[2])

# Multiple indices using a list
indices = [0, 2, 4]
print(arr[indices])

Output:

30
[10 30 50]

Using np.take()

np.take() retrieves elements at specified indices and works with any array dimension:

import numpy as np

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

result = np.take(arr, [0, 2, 4])
print(result)

Output:

[10 30 50]

For 2D arrays, np.take() works on the flattened array by default or along a specific axis:

import numpy as np

arr = np.array([[10, 20, 30],
[40, 50, 60]])

# From flattened array
print(np.take(arr, [0, 3, 5]))

# Along axis=1 (columns)
print(np.take(arr, [0, 2], axis=1))

Output:

[10 40 60]
[[10 30]
[40 60]]

Using Boolean Indexing

Select elements based on a condition:

import numpy as np

arr = np.array([10, 25, 30, 45, 50])

# Get values greater than 25
result = arr[arr > 25]
print(result)

# Get indices where condition is true
indices = np.where(arr > 25)[0]
print(f"Values: {arr[indices]}, at indices: {indices}")

Output:

[30 45 50]
Values: [30 45 50], at indices: [2 3 4]

Setting Values at Specific Indices

Using Direct Assignment

The most straightforward way to set values:

import numpy as np

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

# Set single value
arr[2] = 99
print(arr)

# Set multiple values
arr[[0, 4]] = [100, 500]
print(arr)

Output:

[10 20 99 40 50]
[100 20 99 40 500]

Using np.put() - In-Place Modification

np.put() modifies an array in place by placing values at specified index positions. It works on the flattened version of the array, making it useful for multidimensional arrays.

Syntax:

numpy.put(arr, indices, values, mode='raise')
ParameterDescription
arrTarget array to modify
indicesPositions where values should be placed
valuesValues to insert (broadcasts if shorter than indices)
modeHow to handle out-of-bounds: 'raise', 'wrap', 'clip'

1D Array Example

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
values = [100, 500]

np.put(arr, [0, 4], values)
print(arr)

Output:

[100  20  30  40 500]

2D Array Example

np.put() treats multidimensional arrays as flattened when determining positions:

import numpy as np

arr = np.array([[10, 20, 30],
[40, 50, 60]])

print(f"Original:\n{arr}\n")

# Flattened indices: 0=10, 1=20, 2=30, 3=40, 4=50, 5=60
np.put(arr, [0, 3, 5], [100, 400, 600])

print(f"After put:\n{arr}")

Output:

Original:
[[10 20 30]
[40 50 60]]

After put:
[[100 20 30]
[400 50 600]]

3D Array Example

import numpy as np

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

print(f"Shape: {arr.shape}")

# Replace flattened indices 0, 3, 7
np.put(arr, [0, 3, 7], [10, 40, 80])
print(arr)

Output:

Shape: (2, 2, 2)
[[[10 2]
[ 3 40]]

[[ 5 6]
[ 7 80]]]

Value Broadcasting

If fewer values than indices are provided, values are recycled:

import numpy as np

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

# Single value applied to multiple indices
np.put(arr, [0, 2, 4], 99)
print(arr)

Output:

[99  2 99  4 99]
import numpy as np

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

# Two values cycle across four indices
np.put(arr, [0, 1, 2, 3], [10, 20])
print(arr)

Output:

[10 20 10 20  5  6]

Handling Out-of-Bounds Indices

The mode parameter controls what happens when indices exceed the array size:

mode='raise' (Default) - Raises an Error

import numpy as np

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

try:
np.put(arr, [0, 10], [100, 200], mode='raise')
except IndexError as e:
print(f"Error: {e}")

Output:

Error: index 10 is out of bounds for axis 0 with size 3

mode='clip' - Clips to the Nearest Valid Index

Out-of-bounds indices are clipped to the first or last position:

import numpy as np

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

np.put(arr, [0, 10], [100, 200], mode='clip')
print(arr) # Index 10 clips to index 2 (last element)

Output:

[100  20 200]

mode='wrap' - Wraps Around to the Beginning

Out-of-bounds indices wrap around using modulo:

import numpy as np

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

np.put(arr, [0, 4], [100, 200], mode='wrap')
print(arr) # Index 4 wraps to 4 % 3 = index 1

Output:

[100 200  30]

Using np.put_along_axis() for Advanced Placement

For placing values along a specific axis without flattening:

import numpy as np

arr = np.array([[10, 20, 30],
[40, 50, 60]])

# Replace values at column indices [2, 0] for each row
indices = np.array([[2], [0]])
values = np.array([[99], [88]])

np.put_along_axis(arr, indices, values, axis=1)
print(arr)

Output:

[[10 20 99]
[88 50 60]]

Comparison of Methods

MethodReturnsModifies OriginalWorks on FlattenedBest For
arr[indices]New arrayGetting values
np.take(arr, indices)New array✅ (default)Getting values with axis control
arr[indices] = valuesNoneSimple assignment
np.put(arr, indices, values)NoneIn-place with out-of-bounds handling
np.put_along_axis()NoneAxis-specific placement

Conclusion

To get values at specific indices in a NumPy array, use direct indexing (arr[[0, 2, 4]]) for simplicity or np.take() for more control over axes.

To set values at specific positions, use direct assignment (arr[[0, 2]] = [10, 20]) for straightforward cases or np.put() when you need in-place modification with out-of-bounds handling via mode='raise', 'clip', or 'wrap'.

Remember that np.put() operates on the flattened array, so for multidimensional arrays, calculate your indices based on the flattened position.