2

Whats the most efficient way to update a specific column in numpy? For simplicity, say i have:

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

Then I would like to add 2 on every element on the second column.

[[0 4]
 [1 4]
 [2 4]]

This can be simply done with a loop, but I was wondering if theres a numpy function I could use that would be more efficient. Assuming the array is quite large.

2
  • 2
    Try this: a[:, 1] += 2 You may want to read about Numpy indexing Commented Nov 26, 2017 at 20:55
  • 1
    Arithmetic (and much much more) operations are vectorized in numpy, so just use arr[:,1] += 2. Commented Nov 26, 2017 at 20:55

1 Answer 1

2

You can reference a column using:

a = np.array([[0 2]
              [1 2]
              [2 2]]

a[:,1] += 2
Sign up to request clarification or add additional context in comments.

Comments

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.