Home > Software design >  Python How to replace values in specific columns (defined by an array) with zero
Python How to replace values in specific columns (defined by an array) with zero

Time:07-10

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.

CodePudding user response:

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]]

CodePudding user response:

Since you already know the columns that you want to "zero-out", You can accomplish this by numPy directly:

",1::2" - that means to select cols from 1 to the end by step 2. "1::2"

a[:, 1::2] = 0


>>> a[:, 1::2] = 0
>>> a
array([[1, 0, 3, 0],
       [1, 0, 1, 0],
       [0, 0, 2, 0]])
>>> 

CodePudding user response:

I would do this:

 for j in range(len(a)):
    for k in range(len(a[j])):
        if k in b:
            a[j][k] = 0

CodePudding user response:

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.

  • Related