Add empty column to DataFrame pandas

In this post, we will see how to add empty column to DataFrame pandas.

There are multiple ways to add empty column to DataFrame.
[toc]

Using assignment

You can use assignment to create new columns in python.

import numpy as np
import pandas as pd
df = pd.DataFrame({'Name': ['Vaibhav','Andy','Romi'], "Age": [23,34,28]})
print("-------Original Dataframe-------\n",df)

df['Gender'] = ''
df['Department'] = np.nan
print("-------Updated Dataframe-------\n",df)

Output:

-------Original Dataframe-------
       Name  Age
0  Vaibhav   23
1     Andy   34
2     Romi   28
-------Updated Dataframe-------
       Name  Age Gender  Department
0  Vaibhav   23                NaN
1     Andy   34                NaN
2     Romi   28                NaN

Using reindex() method

You can use DataFrame.reindex() method to create new columns in python.

import pandas as pd
emp_df = pd.DataFrame({'Name': ['Rohan','Martin','Mary'], "Age": [28,39,21]})
print("-------Original Dataframe-------\n",emp_df)

emp_df = emp_df.reindex(columns=emp_df.columns.tolist() + ['Gender','Department'])
print("-------Updated Dataframe-------\n",emp_df)

Output:

-------Original Dataframe-------
      Name  Age
0   Rohan   28
1  Martin   39
2    Mary   21
-------Updated Dataframe-------
      Name  Age  Gender  Department
0   Rohan   28     NaN         NaN
1  Martin   39     NaN         NaN
2    Mary   21     NaN         NaN

If Pandas version is greater than 0.20.0, you can change highlighted line as below:

emp_df = emp_df.reindex(emp_df.columns.tolist() + ['Gender','Department'],axis=1)

Using insert() method

You can use DataFrame.insert() method to create new columns in python. You can use insert() method to add column at any index.
Here is signature of insert() method.

DataFrame.insert(index, Column Header, initial value)

To insert Gender column at first index, you can use:

emp_df.insert(1,'Gender','')
import pandas as pd
emp_df = pd.DataFrame({'Name': ['Rohan','Martin','Mary'], "Age": [28,39,21]})
print("-------Original Dataframe-------\n",emp_df)

emp_df.insert(1,'Gender','')
print("-------Updated Dataframe-------\n",emp_df)

Output:

-------Original Dataframe-------
      Name  Age
0   Rohan   28
1  Martin   39
2    Mary   21
-------Updated Dataframe-------
      Name Gender  Age
0   Rohan          28
1  Martin          39
2    Mary          21

Conclusion

If you just need add empty single column, you can use assignment or insert() method. reindex() method is very convienient in case you need to add multiple empty columns.

That’s all about how to add empty column to DataFrame pandas

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.