简体   繁体   中英

What does this np.append() function mean? [on hold]

my_array=[]
my_array.append(np.where(s==10)[0][1])

s is an array. What does the [0] and [1] in the append function mean?

It is very hard to say without knowing what s is, however, I can explain the logic.

Let's say s looks like this:

>>> s
array([[10, 15, 10],
       [20, 34, 10],
       [23, 10, 19]])

np.where(condition) gives the indices of array where the condition matches. Now if it's a two dimensional array (as in this case) it will return two sets of indices, one for rows, one for columns, like this:

>>> np.where(s==10)
(array([0, 0, 1, 2]), array([0, 2, 2, 1]))

This reads like: (0,0), (0,2), (1,2), (2,1) which are the positions where condition matched.

Now if you wanted the row indices you will need to access the first element (0th index) of the tuple returned by where statement:

>>> np.where(s==10)[0]
array([0, 0, 1, 2])

And now if you wanted the second occurrence of 10 in the row indices, you will need to access the 2nd element (1st index), which is 0

>>> np.where(s==10)[0][1]
0

Now you just append that to empty my_array list:

>>> my_array = []
>>> my_array.append(np.where(s==10)[0][1])
# which essentially means my_array.append(0)
>>> my_array
[0]

NOTE: Please improve your question asking method, refer to this: How do I ask a good question? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM