In this post, we will see how to add empty column to DataFrame pandas.
There are multiple ways to add empty column to DataFrame.
Using assignment
You can use assignment to create new columns in python.
1 2 3 4 5 6 7 8 9 10 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
-------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.
1 2 3 4 5 6 7 8 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
-------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:
1 2 3 |
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.
1 2 3 |
DataFrame.insert(index, Column Header, initial value) |
To insert Gender
column at first index, you can use:
1 2 3 |
emp_df.insert(1,'Gender','') |
1 2 3 4 5 6 7 8 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
-------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