当numpy数组的boolean掩码只是一个值时会发生什么

dffbzjpn  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(106)

我知道boolean数组可以用作numpy数组中的掩码。但是当我在numpy数组中使用单个值作为掩码时,奇怪的事情发生了:

x = [1,2,3,4,5] 
result = np.array(x)[True]
print(result)

[2019 - 04 - 15][2019 - 04 - 15][2019 - 04 - 15][2019 - 04][2019 - 04 - 15][2019 - 04][2019 - 04 - 15][2019 - 04 - 05][2019 - 04 - 05][2019 - 04 - 05][2019 - 04 - 05][2019 - 04 - 05][2019 - 04 - 05][2019 - 04 - 05][2019 - 05][2019 - 05][2019 - 05][2019 - 05][2019 - 05][2019 - 05][2019 - 05]2019 - 05][2019 - 05][2019 - 0为什么会有两个括号?Python在这种情况下会做什么?

t40tm48m

t40tm48m1#

我认为这是由于广播,因为你的输入数组没有正确的形状。
要执行真实的的布尔索引,你需要传递一个list

np.array(x)[[True, False, True, False, True]]
# array([1, 3, 5])

显然,对于[[True]],这将不起作用,因为形状不匹配:

np.array(x)[[True]]
# IndexError: boolean index did not match indexed array along dimension 0;
# dimension is 5 but corresponding boolean dimension is 1

当你运行np.array(x)[True]时,这或多或少相当于:

np.array(x).reshape((1, -1))[[True]]
# array([[1, 2, 3, 4, 5]])

相关问题