Skip to content
Advertisement

How to change inf values in numpy array for the previous non inf value?

I have a numpy array that may contain inf values.

The numpy array is a 1D vector of numbers.

Is there a way to change the inf values of the array for the previous value of the array (which is not inf)?

So if the 1000th index of the array is an inf it should replace it by the 999th index which is not inf.

Heres an example of what I want

vals = np.random.random(10000)
vals[vals<0.1] = np.inf

indexes = np.asarray(vals==np.inf).nonzero()

for i in indexes:
    vals[i] = vals[i-1]

if np.isinf(vals).any():
    print("It doesnt work")
else:
    print("It works")

Advertisement

Answer

why do you not use the simplest way?

for i in range (0,len(a)):
    if a[i]==inf: a[i]=a[i-1]

I have never work with inf. maybe you the type of it is str and so you should write a[i]==’inf’

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement