Python pandas – Create empty column in DataFrame

In this post we will be creating a Python script that will create an empty column within an existing pandas DataFrame.

See below our DataFrame for this example, consisting of three columns ‘Rank’, ‘Name’ and ‘Platform’.

   Rank                       Name Platform
0     1                 Wii Sports      Wii
1     2          Super Mario Bros.      NES
2     3             Mario Kart Wii      Wii
3     4          Wii Sports Resort      Wii
4     5   Pokemon Red/Pokemon Blue       GB
5     6                     Tetris       GB
6     7      New Super Mario Bros.       DS
7     8                   Wii Play      Wii
8     9  New Super Mario Bros. Wii      Wii
9    10                  Duck Hunt      NES
>>> 

Now what one defines as empty columns may differ, this could be a column with nothing inside or a column containing NaN values. In this post we will cover both.

See the snippet of code below where we create an empty column within our pandas DataFrame via empty cells.

import pandas as pd


df["Blank"] = ""
print(df)

The above code would return the following list as output.

   Rank                       Name Platform Blank
0     1                 Wii Sports      Wii      
1     2          Super Mario Bros.      NES      
2     3             Mario Kart Wii      Wii      
3     4          Wii Sports Resort      Wii      
4     5   Pokemon Red/Pokemon Blue       GB      
5     6                     Tetris       GB      
6     7      New Super Mario Bros.       DS      
7     8                   Wii Play      Wii      
8     9  New Super Mario Bros. Wii      Wii      
9    10                  Duck Hunt      NES      
>>> 

See the snippet of code below where we create an empty column within our DataFrame via NaN values.

import pandas as pd
import numpy as np

df=pd.read_csv('Sample.csv')
df["Blank"] = np.nan

print(df)

The above code would return the following list as output.

   Rank                       Name Platform  Blank
0     1                 Wii Sports      Wii    NaN
1     2          Super Mario Bros.      NES    NaN
2     3             Mario Kart Wii      Wii    NaN
3     4          Wii Sports Resort      Wii    NaN
4     5   Pokemon Red/Pokemon Blue       GB    NaN
5     6                     Tetris       GB    NaN
6     7      New Super Mario Bros.       DS    NaN
7     8                   Wii Play      Wii    NaN
8     9  New Super Mario Bros. Wii      Wii    NaN
9    10                  Duck Hunt      NES    NaN
>>> 

Take a look at some of our other content around the Python programming language here. Or check out our Pandas crash course by clicking here instead.

Leave a Reply