【发布时间】:2019-01-13 22:34:09
【问题描述】:
我想根据另一个数组的值更改 numpy 二维数组中的一些值。子矩阵的行选择布尔切片,列选择整数切片。
下面是一些示例代码:
import numpy as np
a = 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 ones
rows = a[:, 3] == 0 # Select all the rows where the value at the 4th column equals 0
cols = [2, 3, 4] # Select the columns 2, 3 and 4
b[rows, cols] = 2 # Replace the values with 2
print(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.]]
但是,我唯一得到的是一个例外:
IndexError
shape mismatch: indexing arrays could not be broadcast together with shapes (5,) (3,)
我怎样才能达到我想要的结果?
【问题讨论】:
-
np.ix_可以将布尔值转换为正确的索引,b[np.ix_(rows, cols)]。最终结果是答案提供的同一对索引数组 - (5,1) 和 (1,3),它们一起广播以索引 (5,3) 块。
标签: python arrays numpy slice submatrix