I have an array. The valid values are not zero (either positive or negetive). I want to find the minimum and maximum within the array which should not take zeros into account. For example if the numbers are only negative. Zeros will be problematic.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
A simple way would be to use a list comprehension to exclude zeros.
You could use a generator expression to filter out the zeros:
Here's another way of masking which I think is easier to remember (although it does copy the array). For the case in point, it goes like this:
It generalizes to other expressions such as a > 0, numpy.isnan(a), ... And you can combine masks with standard operators (+ means OR, * means AND, - means NOT) e.g:
How about:
where
a
is your array.If you can choose the "invalid" value in your array, it is better to use
nan
instead of0
:If this is not possible, you can use an array mask:
Compared to Josh's answer using advanced indexing, this has the advantage of avoiding to create a copy of the array.