Python nan to zero

numpy.nan_to_num#

Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers defined by the user using the nan , posinf and/or neginf keywords.

If x is inexact, NaN is replaced by zero or by the user defined value in nan keyword, infinity is replaced by the largest finite floating point values representable by x.dtype or by the user defined value in posinf keyword and -infinity is replaced by the most negative finite floating point values representable by x.dtype or by the user defined value in neginf keyword.

For complex dtypes, the above is applied to each of the real and imaginary components of x separately.

If x is not inexact, then no replacements are made.

Parameters : x scalar or array_like

copy bool, optional

Whether to create a copy of x (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.

Value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0.

Читайте также:  Python как быстро научиться

Value to be used to fill positive infinity values. If no value is passed then positive infinity values will be replaced with a very large number.

Value to be used to fill negative infinity values. If no value is passed then negative infinity values will be replaced with a very small (or negative) number.

x, with the non-finite values replaced. If copy is False, this may be x itself.

Shows which elements are positive or negative infinity.

Shows which elements are negative infinity.

Shows which elements are positive infinity.

Shows which elements are Not a Number (NaN).

Shows which elements are finite (not NaN, not infinity)

NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.

>>> np.nan_to_num(np.inf) 1.7976931348623157e+308 >>> np.nan_to_num(-np.inf) -1.7976931348623157e+308 >>> np.nan_to_num(np.nan) 0.0 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, -1.2800000e+02, 1.2800000e+02]) >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(y) array([ 1.79769313e+308 +0.00000000e+000j, # may vary 0.00000000e+000 +0.00000000e+000j, 0.00000000e+000 +1.79769313e+308j]) >>> np.nan_to_num(y, nan=111111, posinf=222222) array([222222.+111111.j, 111111. +0.j, 111111.+222222.j]) 

Источник

Numpy – Replace All NaN Values with Zeros

In this tutorial, we will look at how to replace all occurrences of NaN values in a Numpy array with zeros with the help of some examples.

How do I replace all NaN with 0 in Numpy?

replace all nans in a numpy array with zeros

Use boolean indexing to replace all instances of NaN in a Numpy array with zeros. Here, we use the numpy.isnan() function to check whether a value inside the array is NaN or not, and if it is, we set it to zero.

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

The following is the syntax –

import numpy as np ar[np.isnan(ar)] = 0

Let’s now look at a step-by-step example of using the above syntax on a Numpy array.

Step 1 – Create a Numpy array

First, we will create a one-dimensional array that we will be using throughout this tutorial.

import numpy as np # create numpy array ar = np.array([1, 2, np.nan, 3, 4, np.nan, np.nan, 5]) # display the array ar
array([ 1., 2., nan, 3., 4., nan, nan, 5.])

Here, we used the np.array() function to create a Numpy array with some numbers and some NaN values.

Step 2 – Set NaN values in the array to 0 using boolean indexing

Use the numpy.isnan() function to check whether a value in the array is NaN or not. If it is, set it to zero.

Let’s replace all occurrences of NaN in the above array with 0.

# replace nan with zeros ar[np.isnan(ar)] = 0 # display the array ar

You can see that each instance of NaN has been replaced by a 0 in the above array. Note that here we are modifying the original array.

You can also use this method to replace NaN values with 0s in higher-dimensional arrays. For example, let’s apply this method to a two-dimensional array containing some NaN values.

# create a 2D numpy array ar = np.array([ [1, np.nan, 2], [np.nan, 3, 4], [5, np.nan, np.nan] ]) # display the array ar
array([[ 1., nan, 2.], [nan, 3., 4.], [ 5., nan, nan]])

Here, we created a 2D Numpy array containing some NaN values.

Let’s now replace the NaN values in this 2D array with 0s.

# replace nan with zeros ar[np.isnan(ar)] = 0 # display the array ar

The array now has 0s in place of NaNs.

You can similarly use this method to replace NaN values in a Numpy array with any other value.

Summary – Replace NaN values in Numpy array with zeros

In this tutorial, we looked at how to replace all NaN values in a Numpy array with zeros. The following is a short summary of the steps mentioned in this tutorial.

  1. Create a Numpy array (skip this step if you already have an array to operate on).
  2. Use the numpy.isnan() function to check whether a value in the array is NaN or not. If it is, set it to 0 using boolean indexing ar[np.isnan(ar)] = 0

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

This website uses cookies to improve your experience. We’ll assume you’re okay with this, but you can opt-out if you wish.

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

How to replace nan with zero in NumPy array

In this post, we are going to learn how to replace nan with zero in NumPy array, replace nan with values,numpy to replace nan with mean,numpy replaces inf with zero by using the built-in function Numpy Library. To run this program make sure NumPy is already installed.

1. Numpy replaces nan with zero in numpy array

The numpy.nan_to_num() function is used whenever it need to replace nan(not a number) values. It replaces nan values with zero and inf with a finite number in an array. We pass numpy array to nan_to_num() function to replace nan values with zero.This is how to replace nan with zero.

  • import numpy library by using “import numpy as np”
  • Call the numpy library function nan_to_num() to replace nan with zero
import numpy as np ndarray = np.array([[ 5,np.nan, 15, 45], [ 9, 7, 11, 60], [16,10, 19, 70], [18, 26, 20, np.nan], [20, 7, 21, np.nan]]) print(np.nan_to_num(ndarray))
[[ 5. 0. 15. 45.] [ 9. 7. 11. 60.] [16. 10. 19. 70.] [18. 26. 20. 0.] [20. 7. 21. 0.]]

2. Numpy replace nan with 1

In this python program, we are using nan_to_num() we can pass int, float values to nan parameter of nan_to_num() function to replace nan values with the given value. In this python program example, we will learn how to replace nan with 1 in a numpy array.

import numpy as np nparr = np.array([[ 5,np.nan, 15, 45], [ 9, np.nan, 11, 60], [16,10, 19, 70], [18, 26, 20, np.nan], [20, 7, 21, np.nan]]) nparr[np.isnan(nparr)] = 0 print(nparr)
[[ 5. 0. 15. 45.] [ 9. 0. 11. 60.] [16. 10. 19. 70.] [18. 26. 20. 0.] [20. 7. 21. 0.]]

4.np.where() : numpy Replace nan with value

In this example, we are replacing nan with value 9. We can replace nan with any custom value as per need. We will learn how to replace nan with a value. We can replace nan with string value by passing string value instead of value 9.

import numpy as np nparr = np.array([[ 5,np.nan, 15, 45], [ 9, np.nan, 11, 60], [16,10, 19, 70], [18, 26, 20, np.nan], [20, 7, 21, np.nan]]) resarr = np.where(np.isnan(nparr), 9, nparr) print(resarr)
[[ 5. 9. 15. 45.] [ 9. 9. 11. 60.] [16. 10. 19. 70.] [18. 26. 20. 9.] [20. 7. 21. 9.]]

5.np.genfromtxt() : numpy replace nan value with zero

if sometimes we have to read data from CSV files by using np.genfromtxt() function filling_values parameter we can assign value with which we want to replace nan value. In this example, we are replacing nan with zero

import numpy as np nparr = np.array([[ 5,np.nan, 15, 45], [ 9, np.nan, 11, 60], [16,10, 19, 70], [18, 26, 20, np.nan], [20, 7, 21, np.nan]]) nparr = np.genfromtxt('student.csv', delimiter=',', filling_values=0) print(nparr)
[[ 3. 9. 8. 0.] [ 9. 7. 0. 60.] [16. 0. 19. 70.] [18. 0. 20. 80.]]

6. Numpy replace nan with mean

In this python script, we will discuss how to replace nan with mean in a numpy array. We have used the NumPy function nanmean() where we have replaced nan value with a mean value of numpy array.

import numpy as np nparr = np.array([[ 5,np.nan, 15, 45], [ 9, np.nan, 11, 60], [16,10, 19, 70], [18, 26, 20, np.nan], [20, 7, 21, np.nan]]) print('mean:',np.nanmean(nparr)) #replace nan with mean print(np.nan_to_num(nparr, nan=np.nanmean(nparr)))
mean : 23.25 [[ 5. 23.25 15. 45. ] [ 9. 23.25 11. 60. ] [16. 10. 19. 70. ] [18. 26. 20. 23.25] [20. 7. 21. 23.25]]

Источник

Оцените статью