How to add Empty Column to Dataframe in Pandas?
Last Updated :
16 Aug, 2022
In DataFrames, Empty columns are defined and represented with NaN Value(Not a Number value or undefined or unrepresentable value). There are various methods to add Empty Column to Pandas Dataframe in Python.
Method 1: Add Empty Column to Dataframe using the Assignment Operator
We are using the assignment operator to assign empty strings to two newly created columns as “Gender” and “Department” respectively for Pandas Dataframes.
Python3
import numpy as np
import pandas as pd
Mydataframe = pd.DataFrame({ 'FirstName' : [ 'Vipul' ,
'Ashish' ,
'Milan' ],
"Age" : [ 21 , 22 , 23 ]})
print ( "\n\n---Original Dataframe---\n" ,
Mydataframe)
Mydataframe[ 'Gender' ] = ''
Mydataframe[ 'Department' ] = ''
print ( "---Updated Dataframe---\n" ,
Mydataframe)
|
Output:
Method 2: Add Empty Column to Dataframe using the np.nan
We are using np.nan values to two newly created columns as “Gender” and “Department” respectively for Pandas Dataframes(table). Numpy library is used to import NaN value and use its functionality.
Python3
import numpy as np
import pandas as pd
print ( "\n\n---Original Dataframe---\n" ,
Mydataframe)
Mydataframe[ 'Gender' ] = np.nan
Mydataframe[ 'Department' ] = np.nan
print ( "---Updated Dataframe---\n" ,
Mydataframe)
|
Output:
Method 3: Add Empty Column to Dataframe using the None
We are using None values to two newly created columns as “Gender” and “Department” respectively for Pandas Dataframes.
Python3
import numpy as np
import pandas as pd
print ( "\n\n---Original Dataframe---\n" ,
Mydataframe)
Mydataframe[ 'Gender' ] = None
Mydataframe[ 'Department' ] = None
print ( "---Updated Dataframe---\n" ,
Mydataframe)
|
Output:
Method 4: Add Empty Column to Dataframe using Dataframe.reindex().
We created a Dataframe with two columns “First name and “Age” and later used Dataframe.reindex() method to add two new columns “Gender” and ” Roll Number” to the list of columns with NaN values.
Python3
import pandas as pd
Mydataframe = pd.DataFrame({ 'FirstName' : [ 'Preetika' ,
'Tanya' ,
'Akshita' ],
"Age" : [ 25 , 21 , 22 ]})
print ( "---Original Dataframe---\n" ,
Mydataframe)
Mydataframe = Mydataframe.reindex(columns = Mydataframe.columns.tolist()
+ [ 'Gender' , 'Roll Number' ])
print ( "\n\n---Updated Dataframe---\n" ,
Mydataframe)
|
Output:
Method 5: Add Empty Column to Dataframe using Dataframe.insert()
We are using the Dataframe.insert() method on pandas Dataframes to add an empty column “Roll Number”, here we can also insert the column at any index position we want (as here we placed the value at index location 0).
Python3
import pandas as pd
Mydataframe = pd.DataFrame({ 'FirstName' : [ 'Rohan' ,
'Martin' ,
'Mary' ],
"Age" : [ 28 , 39 , 21 ]})
print ( "---Original Dataframe---\n" ,
Mydataframe)
Mydataframe.insert( 0 , 'Roll Number' ,'')
print ( "\n\n---Updated Dataframe---\n" ,
Mydataframe)
|
Output:
Share your thoughts in the comments
Please Login to comment...