Python NumPy在运算符之后添加[],例如where

时间:2019-05-31 15:39:08

标签: python numpy

我是python的新手。我正在尝试了解一些代码。该代码使用NumPy库分析数据流。

in0 = input_items[0]
mask = np.where(in0 > 0.9)[0]
(start, stop) = (mask[0], mask[-1])
blank = int(50e-6*sample_rate) # Skip first 50 us.
start = start+blank
foo = in1[start:stop] > 0.5
preamble_location = np.where(foo)[0][0]

在第二行np.where中返回in0的元素大于0.9的位置。我不明白该行中的[0]是什么。与最后一行类似,我不确定[0] [0]的作用。

2 个答案:

答案 0 :(得分:3)

假设您具有以下数组in0np.where(in0 > 0.9)将返回一个索引元组。

in0 = np.array([0.1, 0.5, 0.95, 1.3, 0.5, 0.2])

可以通过打印类型来检查

print (type(np.where(in0 > 0.9)))
# <class 'tuple'>

该元组的长度为1

print (len(np.where(in0 > 0.9)))
# 1

现在,您需要满足此条件的in0数组的索引。但是np.where返回一个元组。

print (np.where(in0 > 0.9))
# (array([2, 3]),)

要获取索引列表,您需要使用索引[0]

print (np.where(in0 > 0.9)[0])
# [2 3]

现在让我们来讨论关于[0][0]的第二个问题。考虑以下示例:

foo = in0[0:4] > 0.5
print (foo)

# array([False, False,  True,  True])

现在np.where再次返回一个元组,如上所示。要获取索引数组,您需要使用索引[0]对其进行访问。这将返回

preamble_location = np.where(foo)[0]
print (preamble_location)
# [2 3]

现在[0][0]只会返回该索引数组的第一个元素,其值为2。如果使用[0][1],则会得到第二个元素,即3。

preamble_location = np.where(foo)[0][0]
print (preamble_location)
# 2

答案 1 :(得分:0)

这是Numpy的功能:https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

[0]是返回的第一个元素。

赞:

list = [3,2,5]
print(list[0])

返回将是:

3