0

A is an numpy array with shape (6, 8)

I want:

x_id = np.array([0, 3])
y_id = np.array([1, 3, 4, 7])

A[ [x_id, y_id] += 1  # this doesn't actually work.

Tricks like ::2 won't work because the indices do not increase regularly.

I don't want to use extra memory to repeat [0, 3] and make a new array [0, 3, 0, 3] because that is slow.

The indices for the two dimensions do not have equal length.

which is equivalent to:

A[0, 1] += 1
A[3, 3] += 1
A[0, 4] += 1
A[3, 7] += 1

Can numpy do something like this?

Update:

Not sure if broadcast_to or stride_tricks is faster than nested python loops. (Repeat NumPy array without replicating data?)

hamster on wheels
  • 2,771
  • 17
  • 50

1 Answers1

2

You can convert y_id to a 2d array with the 2nd dimension the same as x_id, and then the two indices will be automatically broadcasted due to the dimension difference:

x_id = np.array([0, 3])
y_id = np.array([1, 3, 4, 7])
​
A = np.zeros((6,8))
A[x_id, y_id.reshape(-1, x_id.size)] += 1 

A
array([[ 0.,  1.,  0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
Psidom
  • 209,562
  • 33
  • 339
  • 356