- Using the
float("nan")method - Using the
Decimal("nan")method - Using
math.nan - Using the NumPy library
How to assign NaN to a variable in Python
Key takeaways
NaN stands for “Not a Number,” which represents unrepresentable numeric values in Python.
NaN is commonly used in data analysis to represent missing or undefined data.
We can use
float("nan"),Decimal("nan"),math.nan, ornumpy.nanto assignNaNto a variable.NaN passed to
float()orDecimal()is case insensitive.
Handling missing or undefined data is a common challenge in data analysis and scientific computing. Python provides several methods to represent these missing values including NaN.
Why do we need NaN?
NaN (Not a Number) is a numeric “data type” used to represent any value that’s undefined or unpresentable. It’s a special floating-point value defined by the IEEE 754 standard in 1985. Here are some examples of NaN:
- The result of division by 0 is undefined as a real number and is, therefore, represented by NaN.
- “Square root of a negative number” is an imaginary number that cannot be represented as a real number, so, it is represented by NaN.
- The Python NaN is also assigned to variables, in a computation, that do not have values or where the values have yet to be computed. This is especially useful in several analytical tasks with missing data.
NaN is not the same as infinity in Python.
Assigning a NaN value to Python variables
Python offers different ways to assign NaN to a variable. Here’s how we can do it:
- Using the
float("nan")method - Using the
Decimal("nan")method - Using
math.nan - Using the NumPy library
Note: Multiple methods exist to provide flexibility and consistency. Whether we’re working in core Python or using specialized libraries like
numpyormath, we can use the respective NaN to keep things consistent with the rest of your codebase. Various libraries can also optimize how NaN is managed internally.
Using the float("nan") method
We can create a NaN value using float("nan") in Python, as shown below:
Note that the “NaN” passed to the float is not case sensitive. All of the four variables come out as NaN.
n1 = float("nan")n2 = float("Nan")n3 = float("NaN")n4 = float("NAN")print n1, n2, n3, n4
Using the Decimal("nan") method
We can also use Python’s decimal library instead of floats. For example, we can use the Decimal("Nan") method instead of float("Nan").
from decimal import *n1 = Decimal("nan")n2 = Decimal("Nan")n3 = Decimal("NaN")n4 = Decimal("NAN")print n1, n2, n3, n4
Using math.nan
NaN is also part of the math module in Python 3.5 and onward. This can be used as shown below.
import mathn1 = math.nanprint(n1)print(math.isnan(n1))
We can use math.isnan to check whether a certain variable is NaN or not. We cannot use the regular comparison operator, ==, to check for NaN because NaN is not equal to anything (not even itself!).
Using the NumPy library
NumPy, introduced in 2005 by Travis Oliphant, provides floating point representation of NaN by using numpy.nan. Let’s understand how to use it through the following code example:
import numpy as npn1 = np.nan# Check if a value is NaNprint(np.isnan(n1))
Let’s quickly assess our understanding of NaN values in Python by trying the following quiz:
Quiz!
What is a correct way to assign NaN to a variable in Python?
float("nan")
float("NaN")
float("Nan")
All of the above
In conclusion, we can use Python’s built-in tools and libraries like math, Decimal, and NumPy to manage NaN values effectively, preventing errors and facilitating comprehensive data analysis.
Become a Data Analyst with our comprehensive learning path!
If you're ready to kickstart your career as a data analyst, then our Become a Data Analyst path is designed to take you from your first line of code to landing your first job.
Whether you’re a beginner or looking to transition into a data-driven career, this step-by-step journey will equip you with the skills to turn raw data into actionable insights. Develop expertise in data cleaning, analysis, and storytelling to make informed decisions and drive business success. With our AI mentor by your side, you’ll tackle challenges with personalized guidance. Start your data analytics career today and make your mark in the world of data!
Frequently asked questions
Haven’t found what you were looking for? Contact Us
How can we assign NaN in Python?
How can we assign NaN values in a pandas DataFrame?
How do we add NaN values to a list in Python?
How can we replace a string NaN in Python?
How can we replace NaN with 0 in a pandas DataFrame?
How does pandas check if a value is NaN?
How can we remove NaN values from a NumPy array?
How can we count NaN values in a pandas DataFrame?
Free Resources