我想根据另一个数组的值更改 numpy 2D 数组中的某些值。使用布尔切片选择子矩阵的行,使用整数切片选择列。下面是一些示例代码:import numpy as npa = np.array([ [0, 0, 1, 0, 0], [1, 1, 1, 0, 1], [0, 1, 0, 1, 0], [1, 1, 1, 0, 0], [1, 0, 0, 0, 1], [0, 0, 0, 0, 0],])b = np.ones(a.shape) # Fill with onesrows = a[:, 3] == 0 # Select all the rows where the value at the 4th column equals 0cols = [2, 3, 4] # Select the columns 2, 3 and 4b[rows, cols] = 2 # Replace the values with 2print(b)我在 b 中想要的结果是:[[1. 1. 2. 2. 2.] [1. 1. 2. 2. 2.] [1. 1. 1. 1. 1.] [1. 1. 2. 2. 2.] [1. 1. 2. 2. 2.] [1. 1. 2. 2. 2.]]但是,我唯一得到的是一个例外:IndexErrorshape mismatch: indexing arrays could not be broadcast together with shapes (5,) (3,)我怎样才能达到我想要的结果?
1 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
你可以使用argwhere:
rows = np.argwhere(a[:, 3] == 0)
cols = [2, 3, 4]
b[rows, cols] = 2 # Replace the values with 2
print(b)
输出
[[1. 1. 2. 2. 2.]
[1. 1. 2. 2. 2.]
[1. 1. 1. 1. 1.]
[1. 1. 2. 2. 2.]
[1. 1. 2. 2. 2.]
[1. 1. 2. 2. 2.]]
添加回答
举报
0/150
提交
取消