Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting and replace values from numpy array based on list of index

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?

like image 431
BS98 Avatar asked Feb 27 '26 19:02

BS98


2 Answers

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

like image 166
JST Avatar answered Mar 02 '26 10:03

JST


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.

like image 22
Scott Boston Avatar answered Mar 02 '26 08:03

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!