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

非 Y 不嫁゛ 提交于 2021-02-18 22:08:57

问题


Let 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 would I go about changing values in column 3 based on values in column 2? For instance, If column 3 == 3, column 2 = 9.

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

I've looked at np.any(), but I can't figure out how to alter the array in place.


回答1:


You can use Numpy's slicing and indexing to achieve this. Take all the rows where the third column is 3, and change the second column of each of those rows to 9:

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


来源:https://stackoverflow.com/questions/20355311/how-to-replace-values-in-a-numpy-array-based-on-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!