numpy.nan_to_num() in Python
numpy.nan_to_num() function is used when we want to replace nan(Not A Number) with zero and inf with finite numbers in an array. It returns (positive) infinity with a very large number and negative infinity with a very small (or negative) number.
Syntax : numpy.nan_to_num(arr, copy=True)
Parameters :
arr : [array_like] Input data.
copy : [bool, optional] Whether to create a copy of arr (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True.
Return : [ndarray] New Array with the same shape as arr and dtype of the element in arr with the greatest precision. If arr is inexact, then NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype. If arr is not inexact, then a copy of arr is returned.
Code #1 : Working
# Python program explaining # numpy.nan_to_num() function import numpy as geek in_num = geek.nan print ("Input number : ", in_num) out_num = geek.nan_to_num(in_num) print ("output number : ", out_num) |
Output :
Input number : nan output number : 0.0
Code #2 :
# Python program explaining # numpy.nan_to_num function import numpy as geek in_arr = geek.array([[2, geek.inf, 2], [2, 2, geek.nan]]) print ("Input array : ", in_arr) out_arr = geek.nan_to_num(in_arr) print ("output array: ", out_arr) |
Output :
Input array : [[ 2. inf 2.] [ 2. 2. nan]] output array: [[ 2.00000000e+000 1.79769313e+308 2.00000000e+000] [ 2.00000000e+000 2.00000000e+000 0.00000000e+000]]
Code #3 :
# Python program explaining # numpy.nan_to_num function import numpy as geek in_arr = geek.array([[2, 2, 2], [2, 2, 6]]) print ("Input array : ", in_arr) out_arr = geek.nan_to_num(in_arr) print ("Output array: ", out_arr) |
Output :
Input array : Input array : [[2 2 2] [2 2 6]] Output array: [[2 2 2] [2 2 6]]
Recommended Posts:
- Python | Convert list to Python array
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Reading Python File-Like Objects from C | Python
- Python | Merge Python key values to list
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- Any & All in Python
- SQL using Python | Set 1
- set add() in python
- chr() in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



