[英]What is meant by indexing a numpy array with a conditional statement based on itself?
I'm working on a large library for network analysis and have come across a perplexing line whose calling convention I'm not familiar with.我正在开发一个用于网络分析的大型库,遇到了一条令人困惑的线路,我不熟悉其调用约定。
monitors = [1,2,3,4]
nmonitors = 7 # This value is passed arbitrarily to the function
while len(monitors) < nmonitors:
remaining = np.arange(len(routers)) # len(routers) here is == 5
for i in monitors:
remaining = remaining[remaining != i]
monitors.append(np.random.choice(remaining))
The line in questions in inside the loop which indexes the remaining
array by a conditional based on i
and itself.循环内部问题中的行通过基于
i
和自身的条件索引remaining
数组。 After some debugging it seems to be doing more than just evaluating a bool and indexing the array using that boolean value?经过一些调试后,它似乎不仅仅是评估布尔值并使用该布尔值索引数组?
Would anyone be familiar with this syntax/convention and able to point me to the relevant part of numpy documentation or explain?有没有人熟悉这种语法/约定并能够指出我 numpy 文档的相关部分或解释? I've been searching for hours with no results still, thank you.
我已经搜索了几个小时仍然没有结果,谢谢。
There no special syntax, just a combination of generating a boolean array with a conditional test, and indexing an array with a boolean.没有特殊的语法,只是使用条件测试生成布尔数组和使用布尔值索引数组的组合。
A sample array:一个示例数组:
In [125]: arr = np.arange(4)
In [126]: arr
Out[126]: array([0, 1, 2, 3])
Indexing with a boolean:用布尔值索引:
In [127]: arr[[True,False,True,False]]
Out[127]: array([0, 2])
Creating a boolean with a test:使用测试创建布尔值:
In [128]: (arr%2)==0
Out[128]: array([ True, False, True, False])
In [129]: arr[(arr%2)==0]
Out[129]: array([0, 2])
Or with a test like your example:或者像你的例子一样进行测试:
In [131]: arr!=2
Out[131]: array([ True, True, False, True])
In [132]: arr[arr!=2]
Out[132]: array([0, 1, 3])
So that inner loop is removing all elements equal to monitors
from remaining
, leaving only [0]
?所以内部循环正在从
remaining
删除所有等于monitors
元素,只留下[0]
? The larger loop is buggy, but that has nothing to do with the "syntax" of the boolean indexing.较大的循环有问题,但这与布尔索引的“语法”无关。
It returns a new array of Boolean values, the same dimension of the original remaining
.它返回一个新的布尔值数组,与原始
remaining
维度相同。 For each original element of remaining
, wherever that element is not equal to i
, the equivalent index in the new array is true
.对于
remaining
每个原始元素,只要该元素不等于i
,新数组中的等效索引为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.