3

is it possible to get values from numpy array based on list of indexes like i.e 1 and 3? Then, I want to put another values instead of them.

Here is example:

import numpy as np

array = np.array([0, 1, 2, 8, 4, 9, 1, 2])
idx = [3, 5]

So I want to replace X[3] = 8 and X[5] = 9 with another values but I do not want to this in a loop because I could have large array. Is it a way or maybe a function to do operations like this but not in a loop?

1

2 Answers 2

3

You should use array[idx] = new_values. This approach is much faster than native python loops. But you will have to convert 'idx' and 'new_values' to numpy arrays as well.

import numpy as np

n = 100000
array = np.random.random(n)
idx = np.random.randint(0, n, n//10)
new_values = np.random.random(n//10)
%time array[idx] = new_values

Wall time: 257 µs

def f():
    for i, v in zip(idx, new_values):
        array[i] = v
%time f()

Wall time: 5.93 ms

Sign up to request clarification or add additional context in comments.

Comments

1

Use np.r_:

larr = np.array([0, 1, 2, 8, 4, 9, 1, 2])
larr[np.r_[3, 5]]

Output

array([8, 9])

As @MadPhysicist suggest, using larr[np.array([3, 5])] will work also, and is faster.

2 Comments

Why not just np.array?
larr[np.array([3, 5])]. Not shorter, but faster

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.