BS98
BS98

Reputation: 101

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?

Upvotes: 3

Views: 7110

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

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.

Upvotes: 1

JST
JST

Reputation: 56

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

Upvotes: 3

Related Questions