Home > Software design >  How to zero out specific entries in a 2D numpy array given another array that specifies the indices
How to zero out specific entries in a 2D numpy array given another array that specifies the indices

Time:05-25

I have a (k,n) numpy array (call it D) from which I have to zero out specific entries in that array based on the indices given in another numpy array, say y, that's (n,1).

Here are the 2 indices where D[i,j] has to be set to zero:

  • The index of y is the 2nd element, or j

  • The value of y is the 1st element, or i

I tried doing this:

    tmp = np.where(y==0, 0, D)
    result = np.add(tmp, D[1:,:])

But I'm getting ValueError: operands could not be broadcast together with shapes (3,100) (2,100) . Is there a cleaner way I could zero out those specific elements from D using numpy functions?

CodePudding user response:

I will contrive some D[5,10] and y[10,1] as you didn't provide a MWE. Then, use y as first index through y.ravel() and np.arange(n) as second index. So, D[y.ravel(), np.arange(n)] = 0 will do what you want.

import numpy as np
k, n = 5, 10
y = np.random.randint(0,k, (n,1))
D = np.random.randint(1,n, (k,n))

D[y.ravel(), np.arange(n)] = 0

Output of this contrived example:

print(y.T)
[[0 3 4 2 1 4 4 2 3 2]]

print(D) # Original
[[6 5 8 3 2 8 1 7 9 4]
 [6 1 4 5 1 2 6 1 8 9]
 [4 1 9 3 2 7 2 2 8 1]
 [2 4 1 7 6 2 2 1 3 5]
 [5 7 4 2 1 1 4 7 9 7]]

print(D) # Modified 
[[0 5 8 3 2 8 1 7 9 4]
 [6 1 4 5 0 2 6 1 8 9]
 [4 1 9 0 2 7 2 0 8 0]
 [2 0 1 7 6 2 2 1 0 5]
 [5 7 0 2 1 0 0 7 9 7]]

CodePudding user response:

Let's create D array as:

k = 4
n = 5
D = np.arange(1, k * n   1).reshape(k, n)

Then let y be:

y = np.array([2, 0, 3, 1, 3]).reshape(-1, 1)

The first operation is to get y as a 1-D array:

yy = y[:,0]

Then, to zero out indicated elements, run:

D[yy, np.arange(yy.size)] = 0

i.e. you pass a list of row indices and another list of column indices (of equal size).

The result is:

array([[ 1,  0,  3,  4,  5],
       [ 6,  7,  8,  0, 10],
       [ 0, 12, 13, 14, 15],
       [16, 17,  0, 19,  0]])
  • Related