开发者

Setting values of an array to -inf in Python with scipy/numpy

开发者 https://www.devze.com 2023-01-29 02:43 出处:网络
I have an array that looks like this: a = [ -22347 4448294835 4439587326] I want to set its 0 or smaller values to -inf. I tried the following:

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:

  1. Use an array of floating point numbers instead.

  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消