1

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?

2 Answers 2

2

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

If the performance be of importance, ~np.isfinite can be accelerated with numba accelerator in parallel no-python mode, which will be more faster.

1

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
4
  • Thanks, in the end I went for array[np.isposinf(array)] = 0 and array[np.isnan(array)] = 0.
    – Stücke
    Jul 10, 2022 at 7:28
  • 2
    @Stücke why doing this explicitly, not using np.isfinite as my answer? np.isfinite will be much faster than the used one (as you are mentioning), at least 5 times faster on huge data volumes I have tested.
    – Ali_Sh
    Jul 10, 2022 at 17:48
  • Thanks for the information! I'll check that and adapt your code snippet!
    – Stücke
    Jul 11, 2022 at 7:07
  • @Stücke If the performance is of importance, I have proposed another similar solution using numba accelerator which makes this more faster.
    – Ali_Sh
    Jul 11, 2022 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.