1

I'm trying to replace values in specific columns with zero with python, and the column numbers are specified in another array.

Given the following 2 numpy arrays

a = np.array([[  1,   2,   3,   4],
              [  1,   2,   1,   2],
              [  0,   3,   2,   2]])

and

b = np.array([1,3])

b indicates column numbers in array "a" where values need to be replaced with zero. So the expected output is

            ([[  1,   0,   3,   0],
              [  1,   0,   1,   0],
              [  0,   0,   2,   0]])

Any ideas on how I can accomplish this? Thanks.

r.carnahan
  • 47
  • 3

2 Answers2

2

Your question is:

I'm trying to replace values in specific columns with zero with python, and the column numbers are specified in another array.

This can be done like this:

a[:,b] = 0

Output:

[[1 0 3 0]
 [1 0 1 0]
 [0 0 2 0]]

The Integer array indexing section of Indexing on ndarrays in the numpy docs has some similar examples.

constantstranger
  • 9,176
  • 2
  • 5
  • 19
1

A simple for loop will accomplish this.

for column in b:
    for row in range(len(a)):
        a[row][column] = 0
        
print(a)
[[1 0 3 0]
 [1 0 1 0]
 [0 0 2 0]]
ImajinDevon
  • 287
  • 1
  • 11
  • 2
    iterating over a numpy array sort of defeats the point of using one: https://stackoverflow.com/questions/10112745/python-is-the-iteration-of-the-multidimensional-array-super-slow – Hugh Mungus Jul 11 '22 at 10:05