How to replace values โ€‹โ€‹in a numpy array based on another column?

Say I have the following:

import numpy as np data = np.array([ [1,2,3], [1,2,3], [1,2,3], [4,5,6], ]) 

How do I change the values โ€‹โ€‹in column 3 based on the values โ€‹โ€‹in column 2? For example, if column 3 == 3, column 2 = 9.

 [[1,9,3], [1,9,3], [1,9,3], [4,5,6]] 

I looked at np.any() , but I cannot figure out how to change the array in place.

+6
source share
1 answer

You can use Numpy Crop and Indexing to achieve this. Take all the rows where the third column is 3 , and change the second column of each of these rows to 9 :

 >>> data[data[:, 2] == 3, 1] = 9 >>> data array([[1, 9, 3], [1, 9, 3], [1, 9, 3], [4, 5, 6]]) 
+13
source

Source: https://habr.com/ru/post/959248/


All Articles