Easy way to test if each element in an numpy array lies between two values?

前端 未结 3 693
名媛妹妹
名媛妹妹 2020-12-02 13:02

I was wondering if there was a syntactically simple way of checking if each element in a numpy array lies between two numbers.

In other words, just as numpy.ar

相关标签:
3条回答
  • 2020-12-02 13:27

    You can also center the matrix and use the distance to 0

    upper_limit = 5
    lower_limit = 1
    a = np.array([1,2,3,4,5])
    your_mask = np.abs(a- 0.5*(upper_limit+lower_limit))<0.5*(upper_limit-lower_limit)
    

    One thing to keep in mind is that the comparison will be symmetric on both sides, so it can do 1<x<5 or 1<=x<=5, but not 1<=x<5

    0 讨论(0)
  • 2020-12-02 13:28

    one solution would be:

    a = numpy.array([1,2,3,4,5])
    (a > 1).all() and (a < 5).all()
    

    if you want the acutal array of truth vaues, just use:

    (a > 1) & (a < 5)
    
    0 讨论(0)
  • 2020-12-02 13:53

    Another would be to use numpy.any, Here is an example

    import numpy as np
    a = np.array([1,2,3,4,5])
    np.any((a < 1)|(a > 5 ))
    
    0 讨论(0)
提交回复
热议问题