python - 如何更改满足numpy数组中某些要求的某些列中的值
问题描述
例如,我有一个 numpy 数组:
import numpy as np
a = np.array([[1,1,0,5],
[2,2,9,7],
[3,5,5,7],
[4,8,8,9],
[5,7,3,6],
[6,8,1,9]])
现在,如果第三列的值大于 4,我想将第二列到第四列的值更改为 -1,并删除数组底部的所有值。
结果可能是这样的:
b = np.array([[1,1,0,5],
[5,7,3,6],
[6,8,1,9],
[2,-1,-1,-1],
[3,-1,-1,-1],
[4,-1,-1,-1]])
我怎样才能做到这一点?
解决方案
# find the rows that need to be updated
idx2update = a[:,2] > 4
# update rows with -1
a[idx2update, 1:] = -1
# make a new array with correct order
np.concatenate([a[~idx2update], a[idx2update]])
#[[ 1 1 0 5]
# [ 5 7 3 6]
# [ 6 8 1 9]
# [ 2 -1 -1 -1]
# [ 3 -1 -1 -1]
# [ 4 -1 -1 -1]]