Replace infinity with large finite numbers but fill NaN values in Python

To replace NaN values and infinity with large finite numbers in Python, use the numpy.nan_to_num() method. This function converts non-finite values (NaN, positive infinity, negative infinity) to finite numbers that can be processed normally.

Syntax

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

Parameters

The nan_to_num() function accepts the following parameters ?

  • x ? Input array or scalar
  • copy ? Whether to create a copy (True) or modify in-place (False). Default is True
  • nan ? Value to replace NaN. Default is 0.0
  • posinf ? Value to replace positive infinity. Default is very large positive number
  • neginf ? Value to replace negative infinity. Default is very large negative number

Basic Example

Let's create an array with NaN and infinity values and replace them ?

import numpy as np

# Create array with NaN and infinity values
data = np.array([np.inf, -np.inf, np.nan, -128, 128])

print("Original array:")
print(data)

# Replace non-finite values
result = np.nan_to_num(data)

print("\nAfter nan_to_num():")
print(result)
Original array:
[ inf -inf  nan -128. 128.]

After nan_to_num():
[ 1.79769313e+308 -1.79769313e+308  0.00000000e+000 -1.28000000e+002
  1.28000000e+002]

Custom Replacement Values

You can specify custom values for NaN and infinity replacements ?

import numpy as np

data = np.array([np.inf, -np.inf, np.nan, 10, 20])

# Custom replacement values
result = np.nan_to_num(data, nan=999, posinf=1000, neginf=-1000)

print("Original array:")
print(data)

print("\nWith custom replacements:")
print(result)
Original array:
[ inf -inf  nan  10.  20.]

With custom replacements:
[ 1000.  -1000.   999.    10.    20.]

In-place Modification

Set copy=False to modify the original array instead of creating a new one ?

import numpy as np

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

print("Before modification:")
print(data)

# Modify in-place
np.nan_to_num(data, copy=False, nan=0)

print("After in-place modification:")
print(data)
Before modification:
[ nan  inf   5. -inf]

After in-place modification:
[ 0.00000000e+000  1.79769313e+308  5.00000000e+000 -1.79769313e+308]

Common Use Cases

Scenario Parameters Purpose
Default cleaning nan_to_num(array) Replace NaN with 0, inf with max values
Custom NaN value nan=999 Replace NaN with specific number
Bounded infinity posinf=1000, neginf=-1000 Limit infinity to reasonable range
Memory efficient copy=False Modify array in-place

Conclusion

The numpy.nan_to_num() function is essential for cleaning data with non-finite values. Use custom parameters to control replacement values, and set copy=False for memory-efficient in-place operations.

Updated on: 2026-03-26T19:24:37+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements