Python

NumPy Replaces NaN With 0

The NumPy nan_to_num function allows you to replace NaN with a zero and an inf with a finite number in an array.

Using this article, we will discuss using the nan_to_num function in NumPy. Stay tuned!!

Function Syntax

The function syntax is illustrated in the code snippet shown below:

numpy.nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None)

Function Parameters

The function takes the following parameters:

  1. x – defines the input value to be replaced. This is a required parameter, either a scalar value or an array_like object.
  2. copy – a Boolean value that determines if the function will create a copy of the input (no effect on the original) or perform the replacement in-place(affects the initial input).
  3. nan ­ – this is an optional parameter that sets the value used to replace all NaN occurrences in the input array. If the value is not specified, the function will replace NaN values with a 0.
  4. posinf – this value replaces all the positive infinity values. If not determined, a very large number of positive infinity values are replaced.
  5. neginf – this value fills all the negative infinity values. If not specified, all the negative infinity values will be replaced with a very small (or negative) number.

Return Value

The function returns the input array with the non-finite values replaced. If the copy is false, the function will act in place.

Example

The example below shows how to use the nan_to_num function to replace NaN values with 0.

import numpy as np
arr = np.array([np.nan, 1, 2,3])
print(f"orignal: {arr}")
copy = np.nan_to_num(arr, copy=True)
print(f"copy: {copy}")

In the example above, we replace the NaN values in the input array. The resulting output is as shown:

orignal: [nan  123.]
copy:    [0. 1. 2. 3.]

Example Code 2

The example below illustrates the nan_to_num function used with infinite values.

arr = np.array([np.nan, -np.inf, np.inf, -100, 100])
print(np.nan_to_num(arr, copy=False))

The example above uses the nan_to_num function to replace all positive and negative infinite values of the NaN values.

The result is as shown below:

[ 0.00000000e+000 -1.79769313e+308  1.79769313e+308 -1.00000000e+002
1.00000000e+002]

Closing

In this article, we cover how to use the NumPy nan_to_num() function to replace NaN values with 0 and all positive and negative integer values. Feel free to explore the docs for more.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list