Setting values of an array to -inf in Python with scipy/numpy
I have an array that looks like this:
a = [ -22 347 4448 294 835 4439 587 326]
I want to set its 0 or smaller values to -inf. I tried the following:
a[where(a <= 0)] = -inf
when I do this, I get the error:
OverflowError: cannot convert flo开发者_Go百科at infinity to integer
Any idea why this is and how I can fix it? the "where" function should return the indices of values less than or equal to 0, and the assignment should just set those values to -inf. thanks.
Your array a
is an array of integers. Integers can't represent infinity -- only floating point numbers can. So there are to fixes:
Use an array of floating point numbers instead.
Use a large negative integer value, e.g.
-2147483648
if you are using 32-bit integers. Of course that's not the same as -infinity, but in some contexts it behaves similar.
Furthermore, you can simply write
a[a <= 0] = <somevalue>
If your array's type is integer, you won't be able to set any values to -infinity
. That's a special value in IEEE floating point. The obvious way to fix it is to use an array of floats.
精彩评论