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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Do you need additional help with your question?
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]]

1 Comment

iterating over a numpy array sort of defeats the point of using one: stackoverflow.com/questions/10112745/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.