1

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]
1
  • I can't think of one, no. Commented Apr 10, 2019 at 14:28

1 Answer 1

1

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.

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

Comments

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.