0

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")

2 Answers2

1
def pandas_fill(arr):
    df = pd.DataFrame(arr)
    df.fillna(method='ffill', axis=1, inplace=True)
    out = df.as_matrix()
    return out

def numpy_fill(arr):
    mask = np.isnan(arr)
    idx = np.where(~mask,np.arange(mask.shape[1]),0)
    np.maximum.accumulate(idx,axis=1, out=idx)
    out = arr[np.arange(idx.shape[0])[:,None], idx]
    return out

inf and -inf will be loaded as nan. So, this should be handled with that.

Try out this updated one.

import numpy as np

Data = np.array([np.nan,1.3,np.nan,1.4,np.nan,np.nan])

nansIndx = np.where(np.isnan(Data))[0]
isanIndx = np.where(~np.isnan(Data))[0]
for nan in nansIndx:
    replacementCandidates = np.where(isanIndx>nan)[0]
    if replacementCandidates.size != 0:
        replacement = Data[isanIndx[replacementCandidates[0]]]
    else:
        replacement = Data[isanIndx[np.where(isanIndx<nan)[0][-1]]]
    Data[nan] = replacement
print(Data)
Rajnish kumar
  • 186
  • 1
  • 14
1

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'

Reihaneh Kouhi
  • 489
  • 1
  • 7
  • 23