如何解释numpy输出的逻辑过程?[副本]

yhxst69z  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(94)

此问题已在此处有答案

Weird Boolean Indexing Output(1个答案)
4天前关闭。
我从起始页开始学习numpy:https://numpy.org/devdocs/user/quickstart.html有一个令人困惑的部分让我停下来。

>>> a = np.arange(12).reshape(3, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> b1 = np.array([False, True, True])         # first dim selection
>>> b2 = np.array([True, False, True, False])  # second dim selection
>>> a[b1, b2]
array([ 4, 10])

你能提供一些提示或解释来帮助我理解这个逻辑吗?我期望的输出是

array([[ 4,  6],
       [ 8, 10]])
puruo6ea

puruo6ea1#

一个简单的方法来实现你想要的是应用你的面具顺序。换句话说

a[b1,:][:,b2]

# [[ 4  6]
# [ 8 10]]

看起来好像您假设b1确定必须选择哪些行,b2确定必须选择哪些列。这是一个公平的假设,但numpy面具的传播方式不同。实际上,当你同时传递 * 两者 * 时,它们会被转换为索引。所以呢

b1 = np.array([False, True, True]) -> [1,2]
b2 = np.array([True, False, True, False]) -> [0,2]

这确实给了“怪异”的行为:

b1 = [1,2]
b2 = [0,2]

a[b1,b2] # [ 4 10]

相关问题