Reputation: 335
I'm super new to python. I'm trying to understand some code. The code uses the NumPy library to analyze a data stream.
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]
In the second line np.where returns where the elements of in0 are greater than 0.9. What I don't understand is what the [0] in that line does. Similar to the last line I'm not sure what [0][0] does as well.
Upvotes: 0
Views: 43
Reputation: 39072
Suppose you have the following array in0
. np.where(in0 > 0.9)
will return you a tuple of indices.
in0 = np.array([0.1, 0.5, 0.95, 1.3, 0.5, 0.2])
This can be checked by printing the type
print (type(np.where(in0 > 0.9)))
# <class 'tuple'>
The length of this tuple is 1
print (len(np.where(in0 > 0.9)))
# 1
Now you need the indices of in0
array which fulfill this condition. But np.where
returns a tuple.
print (np.where(in0 > 0.9))
# (array([2, 3]),)
To get the list of indices, you need to use the index [0]
print (np.where(in0 > 0.9)[0])
# [2 3]
Now let's come to the second question about [0][0]
. Consider the following example:
foo = in0[0:4] > 0.5
print (foo)
# array([False, False, True, True])
Now np.where
again returns a tuple as shown above. To get the array of indices, you need to access it using index [0]
. This will return
preamble_location = np.where(foo)[0]
print (preamble_location)
# [2 3]
Now [0][0]
will just return the first element of this array of indices, which is the value 2. If you use [0][1]
, you will get the second element i.e., 3.
preamble_location = np.where(foo)[0][0]
print (preamble_location)
# 2
Upvotes: 3
Reputation: 863
It's a function of Numpy : https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
[0]
is the first element of the return.
Like :
list = [3,2,5]
print(list[0])
The return will be :
3
Upvotes: 0