How to Add a NaN Value in Python Dataframe

To add a NaN value to a DataFrame in Python, you can use the Numpy library.

The following example shows how to add a NaN value to a DataFrame.

Use np.nan to Add NaN Value to DataFrame

We can use np.nan to add a NaN value to a DataFrame.

Suppose we have the following DataFrame:

# Import libraries
import pandas as pd
import numpy as np

# Create dataframe
office_stuff = pd.DataFrame({
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
})

# Add a NaN value in the Price column
office_stuff.at[3, 'Price'] = np.nan

# Show updated dataframe
print(office_stuff)

Output: 👇️

         Date Product_Code Product_Name   Price  Status
0  01-03-2023        A-101       Laptop  4500.0       1
1  01-03-2023        A-102       Mobile   550.0       1
2  01-03-2023        A-103      Printer   250.0       1
3  01-03-2023        B-101     Keyboard     NaN       0
4  02-03-2023        B-102      Scanner   350.0       1
5  02-03-2023        B-104        Mouse    50.0       1

In this example, we add a NaN value to the Price column at position 3.