Ways to Create NaN Values in Pandas DataFrame

Let’s discuss ways of creating NaN values in the Pandas Dataframe. There are various ways to create NaN values in Pandas dataFrame. Those are:

  • Using NumPy
  • Importing csv file having blank values
  • Applying to_numeric function

Method 1: Using NumPy

filter_none

edit
close

play_arrow

link
brightness_4
code

import pandas as pd
import numpy as np
  
num = {'number': [1,2,np.nan,6,7,np.nan,np.nan]}
df = pd.DataFrame(num)
  
df

chevron_right


Output:

pandas-create-nan-11

Method 2: Importing the CSV file having blank instances



Consider the below csv file named “Book1.csv”:


Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

# import pandas
import pandas as pd
  
# read file
df = pd.read_csv("Book1.csv")
  
# print values
df

chevron_right


Output:

pandas-create-nan-2

You will get Nan values for blank instances.

Method 3: Applying to_numeric function

to_numeric function coverts arguments to a numeric type.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

import pandas as pd
  
num = {'data': [1,"hjghjd",3,"jxsh"]}
df = pd.DataFrame(num)
  
# this will convert non-numeric 
# values into NaN values
df = pd.to_numeric(df["data"], errors='coerce')
  
df

chevron_right


Output:

pandas-create-nan-4




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.