Numpy: find index of the elements within range

前端 未结 12 2240
盖世英雄少女心
盖世英雄少女心 2020-11-28 23:01

I have a numpy array of numbers, for example,

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  

I would like to find all the indexes of the

12条回答
  •  迷失自我
    2020-11-28 23:13

    This code snippet returns all the numbers in a numpy array between two values:

    a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56] )
    a[(a>6)*(a<10)]
    

    It works as following: (a>6) returns a numpy array with True (1) and False (0), so does (a<10). By multiplying these two together you get an array with either a True, if both statements are True (because 1x1 = 1) or False (because 0x0 = 0 and 1x0 = 0).

    The part a[...] returns all values of array a where the array between brackets returns a True statement.

    Of course you can make this more complicated by saying for instance

    ...*(1-a<10) 
    

    which is similar to an "and Not" statement.

提交回复
热议问题