When using an ndarray to represent a matrix, how to modify a column based on the value of another column?

Question:

Numpy’s documentation suggests to use numpy arrays to represent matrices, so I’m looking at something like

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

to represent

enter image description here

and I just can’t figure out from the documentation how I would update a column based on the value of another column. Say, how would I do something like: If, in any row, the value in the second column is > 3, then add 10 to the third? Ie, in my example, I’d like to obtain:

enter image description here

Alternatively, kindly advise if there is some conceptional misunderstanding on my part about ndarrays. I’m really new to this…

Asked By: johnl

||

Answers:

The specific task you’re interested can be done as follows

arr[arr[:,1]>3,2] += 10
Answered By: Ben Grossmann
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.