NaN in Python
NaN or Not a Number is considered to be a value that is either undefined or missing, for example, in any dataset any values that are missing could be defined as NaN value, the NaN value works as a placeholder here, which some other value could later replace. However, it still has a mathematical significance to it, it usually works as a placeholder when there is a computational problem and the value of every cell is important, therefore, considering the value to be NaN keeps the data consistent. The NaN value in Python could be represented as:
float("nan")
NaN values are commonly used for scientific computational purposes since a lot of real-world data might miss some of the data values. For example, if we want to find out the square root of a negative number let’s say -5 the output will be NaN value in NumPy.
Python3
import numpy as np result = np.sqrt( - 1.0 ) print (f "The resulting value is '{result}' which has the datatype {type(result)}" ) |
Output:
The resulting value is 'nan' which has the datatype <class 'numpy.float64'>
Identifying if NaN Values are Present in the Dataset
We can identify if a NaN value is present in the dataset by importing it into the Pandas library, here is a code example to exactly do that:
First we will be importing important libraries NumPy for mathematical computing and Pandas for data manipulation and then creating a Python dictionary and converting it into a Pandas DataFrame and then printing it.
Python3
import pandas as pd import numpy as np # Create a DataFrame with some NaN values data = { 'A' : [ 1 , 2 , np.nan, 4 ], 'B' : [ 5 , np.nan, np.nan, 8 ], 'C' : [ 10 , 11 , 12 , 13 ] } df = pd.DataFrame(data) # Printing the DataFrame print ( "DataFrame:" ) print (df) |
Output:
DataFrame:
A B C
0 1.0 5.0 10
1 2.0 NaN 11
2 NaN NaN 12
3 4.0 8.0 13
Difference Between Nan and None in Python
Python is a dynamically typed language with multiple concepts which might get confusing as we get to the computational parts of the Python language. Understanding basic concepts becomes a part of getting to know about the thought process of working with such concepts. One of such ambiguities arrives when comparing two same-sounding but different concepts in Python named NaN value and None value. In this article, we will be discussing the difference between the NaN value and the None value in Python.