Home > Software engineering >  Alternative for `nan_to_num()`
Alternative for `nan_to_num()`

Time:07-09

I am using the following code on a high computation cluster:

array = np.nan_to_num(
     array,
     copy = False,
     # Replace
     nan = 0.0,
     posinf = 0.0,
     neginf = 0.0
)

The code causes the following error:

Module for Anaconda3 2019.03 loaded.
Run script ...
Traceback (most recent call last):
  File "test.py", line 118, in <module>
    neginf = 0.0
TypeError: nan_to_num() got an unexpected keyword argument 'nan'
Done

I googled the error. Apparently, my code can only be run by NumPy > v1.17. The high computation cluster environment uses NumPy v1.16.2 and Python v3.7.3.

What code snippet can replace my code snippet above?

CodePudding user response:

Use the property that Nan!=Nan

array[array!=array] = nan_value

And compare with np.inf for infinite values:

array[array==np.inf] = pos_inf_value
array[array==(-np.inf)] = neg_inf_value

CodePudding user response:

You can revert np.isfinite to get non-finite values and modify them by indexing:

array[~np.isfinite(array)] = 0.0

little explanation:

array = np.array([np.nan, np.inf, -np.inf, 3])

np.isfinite(array)
# [False False False  True]

~np.isfinite(array)
# [ True  True  True False]

array[~np.isfinite(array)] = 0.0
# [0. 0. 0. 3.]
  • Related