r.carnahan
r.carnahan

Reputation: 47

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

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.

Upvotes: 1

Views: 846

Answers (2)

constantstranger
constantstranger

Reputation: 9379

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.

Upvotes: 2

ImajinDevon
ImajinDevon

Reputation: 317

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

Upvotes: 1

Related Questions