Replace -inf with zero value
Asked Answered
M

3

70

I have an array:

x =  numpy.array([-inf, -inf, 37.49668579])

Is there a way to change the -inf values to just 0?

Mirador answered 10/1, 2014 at 16:50 Comment(0)
Q
108

There is:

from numpy import inf
x[x == -inf] = 0
Queue answered 10/1, 2014 at 16:56 Comment(6)
this is around 20% faster than np.isneginf based on my testCondominium
How are the brackets used here? Is this indexing with a conditional, or list comprehension?Armistead
No list comprehension. It is numpy indexing using a boolean array. In this case: "Elements of x equal to -inf".Pinnatisect
NameError: global name 'inf' is not definedSinister
@johnktejik did you run the import statement from numpy import inf ?Lahey
I believe it's better to use X[~np.isfinite(X)] = 0 or x[numpy.isneginf(x)] = 0 as in the second answerCoheman
R
27

Perhaps even easier and more flexible to use numpy.nan_to_num:

numpy.nan_to_num(x, neginf=0) 

Out[1]: array([ 0.        ,  0.        , 37.49668579])
Rottweiler answered 18/12, 2020 at 15:22 Comment(0)
B
25

Use isneginf http://docs.scipy.org/doc/numpy/reference/generated/numpy.isneginf.html#numpy.isneginf

x[numpy.isneginf(x)] = 0
Boonie answered 10/1, 2014 at 17:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.