How to count values in a certain range in a Numpy array?

后端 未结 5 840
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 12:27

I have a NumPy array of values. I want to count how many of these values are in a specific range say x<100 and x>25. I have read about the counter, but it seems to on

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 13:12

    Building on Sven's good approach, you can also do the slightly more explicit:

    numpy.count_nonzero((25 < a) & (a < 100))
    

    This first creates an array of booleans with one boolean for each input number in array a, and then count the number of non-False (i.e. True) values (which gives the number of matching numbers).

    Note, however, that this approach is twice as slow as Sven's .sum() approach, on an array of 100k numbers (NumPy 1.6.1, Python 2.7.3)–about 300 µs versus 150 µs.

提交回复
热议问题