3

I have three arrays, indices, values, and replace_values. I have to loop over indices, replacing each value in old_values[indices[i]] with new_values[i]. What's the fastest possible way to do this? It feels like there should be some way to speed it up using NumPy functions or advanced slicing instead of the normal for loop.

This code works, but is relatively slow:

import numpy as np

# Example indices and values
values = np.zeros([5, 5, 3]).astype(int)

indices = np.array([[0,0], [1,0], [1,3]])
replace_values = np.array([[140, 150, 160], [20, 30, 40], [100, 110, 120]])

print("The old values are:")
print(values)

for i in range(len(indices)):
    values[indices[i][0], indices[i][1]] = replace_values[i]

print("The new values are:")
print(values)

1 Answer 1

2

Use zip to separate x and y indices, then cast to tuple and assign:

>>> values[tuple(zip(*indices))] = replace_values
>>> values

array([[[140, 150, 160],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[ 20,  30,  40],
        [  0,   0,   0],
        [  0,   0,   0],
        [100, 110, 120],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]],

       [[  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0],
        [  0,   0,   0]]])

Where tuple(zip(*indices)) returns:

((0, 1, 1), (0, 0, 3))

As your indices is np.array itself, you can remove zip and use transpose, as pointed out by @MadPhysicist:

>>> values[tuple(*indices.T)]
Sign up to request clarification or add additional context in comments.

1 Comment

tuple(zip(*indices)) would be much more effiently written as tuple(*indices.T). That way, you make a tuple from two arrays instead of converting each element into an int object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.