python-np.在索引特定范围时,这里很奇怪



嗨,我从python开始。。

我发现在python 中使用np.where((对我来说有些不好理解的地方

aaa = np.array([1,2,3,4,5,6,7,8,9,10])
np.where(aaa[3:5] > 4)

我所期望的:[4]

我得到的:(array([1]),)

有人帮忙吗?感谢您阅读

您正在索引切片aaa->aaa[3:5]这个新数组看起来像array([4, 5]),并且这个新数组大于4的地方在位置1(因为数组从0开始(。

此外,当只给定一个条件时,np.where返回一个元组:

如果只给定条件,则返回元组条件.nonzero((条件为True 的索引

因此结果是元组:

(array([1]),)

将np.where行替换为

np.where(aaa>4)[0][0]

这是正确的,

np.where(...)文档中,我们看到,当省略x,y时,它会调用np.nonzero(...),就像您的情况一样。

什么是np.nonzero(...)

返回非零元素的索引。

并且它在这里返回True的位置。

>>> aaa[3:5] > 4
array([False,  True])

对这种现象的解释如下:

当您对原始数组进行切片时,会通过aaa[3:5]返回一个新数组。np.where返回您传递给它的数组中匹配项的索引。因此,要查看实际结果,您需要使用相同的数组:

import numpy as np
aaa = np.array([1,2,3,4,5,6,7,8,9,10])
print(aaa[3:5])    # remember, array index count starts from 0
# [4 5]
idx = np.where(aaa[3:5] > 4)   # we are NOT looking in the original array
print(idx)
# (array([1]),)
# So, only one element matches the criteria in the given array, its index in the NEW array is returned
print(aaa[3:5][idx])
#[5] 

请记住,在这种情况下,np.where返回的索引不应用于从原始数组中提取元素,而只能用于从新数组

相关内容

最新更新