Function Repository Resource:

ReplaceNaN

Source Notebook

Replace all IEEE 754 NaN values in an array with custom representations

Contributed by: Ting Sun

ResourceFunction["ReplaceNaN"][data]

replaces all IEEE 754 NaN values of array data with Indeterminate.

ResourceFunction["ReplaceNaN"][data,rep]

replaces all IEEE 754 NaN values of array data with custom representation rep.

Details

IEEE 754 NaN values are usually imported as real numbers via LibraryLink or other external numeric systems (e.g. NumPy) and often need to be converted to Indeterminate for further computation.

Examples

Basic Examples (2) 

Introduce an array from NumPy including IEEE 754 NaN values and replace them with Indeterminate:

In[1]:=
xArray = ExternalEvaluate["Python", "import numpy as np; x=np.random.random_sample([3,2]);x[[1,2],[0,1]]=np.nan;x"] // Normal;
ResourceFunction["ReplaceNaN"][xArray]
Out[2]=

NaN values can also be replaced by custom representations:

In[3]:=
ResourceFunction["ReplaceNaN"][xArray, -999.]
Out[3]=

Applications (1) 

Use Nothing as custom representation for NaN to clean up an array:

In[4]:=
ResourceFunction["ReplaceNaN"][xArray, Nothing]
Out[4]=

Possible Issues (2) 

Direct computation involving NaN values may result in unexpected results:

In[5]:=
xArray + 1 - xArray
Out[5]=

NaNs should be replaced by Indeterminate for further computation:

In[6]:=
With[{xArrayCorrected = ResourceFunction["ReplaceNaN"][xArray]}, xArrayCorrected + 1 - xArrayCorrected]
Out[6]=

Publisher

Ting Sun

Version History

  • 1.0.0 – 26 April 2021

Related Resources

License Information