Ways to Create NaN Values in Pandas DataFrame
Last Updated :
08 Dec, 2021
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
Python3
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
|
Output:
Method 2: Importing the CSV file having blank instances
Consider the below csv file named “Book1.csv”:
Code:
Python3
import pandas as pd
df = pd.read_csv( "Book1.csv" )
df
|
Output:
You will get Nan values for blank instances.
Method 3: Applying to_numeric function
to_numeric
function converts arguments to a numeric type.
Example:
Python3
import pandas as pd
num = { 'data' : [ 1 , "hjghjd" , 3 , "jxsh" ]}
df = pd.DataFrame(num)
df = pd.to_numeric(df[ "data" ], errors = 'coerce' )
df
|
Output:
Share your thoughts in the comments
Please Login to comment...