如何替换基于另一列的numpy数组中的值? [英] How to replace values in a numpy array based on another column?
本文介绍了如何替换基于另一列的numpy数组中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我说以下内容:
import numpy as np
data = np.array([
[1,2,3],
[1,2,3],
[1,2,3],
[4,5,6],
])
如何根据第2列中的值更改第3列中的值?例如,如果第3列== 3,则第2列=9.
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]]
我看过 np.any()
,但是我不知道如何在适当的位置更改数组.
I've looked at np.any()
, but I can't figure out how to alter the array in place.
推荐答案
您可以使用 Numpy的切片和索引来实现这一目标.取第三列为 3
的所有行,并将每行的第二列更改为 9
:
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]])
这篇关于如何替换基于另一列的numpy数组中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文