4

Reproducible setup

I have an array of n pairs of indices:

indexarray=\
np.array([[0,2,4,6],
          [1,3,5,7]])

I also have a 2D array:

zeros = np.zeros((10,9))

and a list of n values:

values = [1,2,3,4]

I would like to add each kth element from the values list to the element in the zeros list having indeces equal to the kth indices pair

A solution

# works, but for loop is not suitable for real-world use-case
for index, (row, col) in enumerate(indexarray.T):
    zeros[row, col] = values[index]

Visualize what I get:

plt.imshow(zeros)

enter image description here

Results as expected.

How can I do this without iteration?


Similar but different questions:

4
  • 1
    rows, cols = indexarray[0], indexarray[1]; zeros[rows, cols] = values? Commented Nov 12, 2021 at 10:58
  • Wow, cannot believe I've missed that :) Thanks! Commented Nov 12, 2021 at 10:59
  • Are you going to have repeated indices? Do you need to add them together? Commented Nov 12, 2021 at 11:01
  • 1
    Personally I don't need that, but future users finding this question might; feel free to add an answer covering that case as well if you feel like it - my problem at hand is solved. Commented Nov 12, 2021 at 11:03

3 Answers 3

4

Simply use:

import numpy as np

indexarray = np.array([[0, 2, 4, 6],
                       [1, 3, 5, 7]])
values = [1, 2, 3, 4]

rows, cols = indexarray[0], indexarray[1]

zeros = np.zeros((10, 9))
zeros[rows, cols] = values

print(zeros)

Output

[[0. 1. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 2. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 3. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 4. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]]

An alternative that will add together repeating coordinates, is to use add.at:

np.add.at(zeros, (rows, cols), values)

A second alternative is to use a sparse matrix constructor, for example:

from scipy.sparse import csr_matrix
rows, cols = indexarray[0], indexarray[1]
zeros = csr_matrix((values, (rows, cols)), shape=(10, 9)).toarray()

Output

[[0 1 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 2 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 3 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 4 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0]]
Sign up to request clarification or add additional context in comments.

Comments

1

You can directly use indexarray in indexing.

r, c = indexarray
zeros[r, c] = values

Comments

1

You can simply use:

zeros[indexarray[0], indexarray[1]] = values

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.