mon*_*mon 9 python numpy boolean-indexing
对于二维数组 y:
y = np.arange(20).reshape(5,4)
---
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
Run Code Online (Sandbox Code Playgroud)
所有索引都选择第 1、第 3 和第 5 行。这是清楚的。
print(y[
[0, 2, 4],
::
])
print(y[
[0, 2, 4],
::
])
print(y[
[True, False, True, False, True],
::
])
---
[[ 0 1 2 3]
[ 8 9 10 11]
[16 17 18 19]]
Run Code Online (Sandbox Code Playgroud)
请帮助了解产生结果的规则或机制。
[]用元组替换会产生一个形状为 (0, 5, 4) 的空数组。
y[
(True, False, True, False, True)
]
---
array([], shape=(0, 5, 4), dtype=int64)
Run Code Online (Sandbox Code Playgroud)
使用 singleTrue添加一个新轴。
y[True]
---
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]]])
y[True].shape
---
(1, 5, 4)
Run Code Online (Sandbox Code Playgroud)
添加额外的布尔值 True 会产生相同的结果。
y[True, True]
---
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]]])
y[True, True].shape
---
(1, 5, 4)
Run Code Online (Sandbox Code Playgroud)
但是,添加 False 布尔值会再次导致空数组。
y[True, False]
---
array([], shape=(0, 5, 4), dtype=int64)
Run Code Online (Sandbox Code Playgroud)
不确定文档解释了这种行为。
通常,如果索引包含布尔数组,结果将与将 obj.nonzero() 插入相同位置并使用上述整数数组索引机制相同。x[ind_1, boolean_array, ind_2] 等价于 x[(ind_1,) + boolean_array.nonzero() + (ind_2,)]。
如果只有一个布尔数组而没有整数索引数组,这很简单。只需要注意确保布尔索引具有与它应该使用的维度一样多的维度。
布尔标量索引没有详细记录,但您可以跟踪它在源代码中的处理方式。例如,请参阅numpy 源中的此注释和相关代码:
/*
* This can actually be well defined. A new axis is added,
* but at the same time no axis is "used". So if we have True,
* we add a new axis (a bit like with np.newaxis). If it is
* False, we add a new axis, but this axis has 0 entries.
*/
Run Code Online (Sandbox Code Playgroud)
因此,如果索引是标量布尔值,则会添加一个新轴。如果该值为 False True,则轴的大小为 1,如果该值为 False,则轴的大小为零。
这种行为是在numpy#3798中引入的,作者在这条评论中概述了动机;粗略地说,目的是提供过滤操作输出的一致性。例如:
x = np.ones((2, 2))
assert x[x > 0].ndim == 1
x = np.ones(2)
assert x[x > 0].ndim == 1
x = np.ones(())
assert x[x > 0].ndim == 1 # scalar boolean here!
Run Code Online (Sandbox Code Playgroud)
有趣的是,第一个之后的任何后续标量布尔值都不会添加额外的维度!从实现的角度来看,这似乎是由于连续的 0D 布尔索引被视为等同于连续的花式索引(即在某些情况下HAS_0D_BOOL被视为HAS_FANCY),因此以与花式索引相同的方式组合。从逻辑的角度来看,这种极端情况的行为似乎不是故意的:例如,我在numpy#3798中找不到任何关于它的讨论。
鉴于此,我建议考虑这种定义不明确的行为,并避免它,转而采用记录良好的索引方法。