LRMB33
LRMB33

Reputation: 53

Assign values to multiple columns of numpy matrix without looping

I have a numpy matrix X with n columns, and I have a list I of n lists of indices i, and a corresponding list V of n lists of values v. For each column c in X, I want to assign the indices I[c] to the values V[c]. Is there a way to do this without a for loop, i.e.:

n = 3
X = np.zeros((4,n))
I = [[0,1],[1,2,3],[0]]
V = [[1,1],[2,2,2],[3]]

for c in range(n):
    X[I[c],c] = V[c]

Upvotes: 1

Views: 339

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53119

True vectorization I can't see, but no explicit for loops is doable:

X[np.concatenate(I), np.arange(len(I)).repeat(np.vectorize(len)(I))] = np.concatenate(V)
X
# array([[1., 0., 3.],
#        [1., 2., 0.],
#        [0., 2., 0.],
#        [0., 2., 0.]])

But I'm not sure this will be any faster than a for loop.

Upvotes: 1

Related Questions