How to add an empty column to an existing dataframe with pandas ?

Published: March 18, 2021

Tags: Python; Pandas; DataFrame;

DMCA.com Protection Status

Example of how to add an empty column to an existing dataframe with pandas

Create a dataframe

Let's create a dataframe with pandas:

import pandas as pd
import numpy as np

data = np.random.randint(10, size=(5,2))

df = pd.DataFrame(data=data,columns=['A','B'])

print(df)

returns for example

   A  B
0  4  8
1  9  9
2  1  4
3  6  4
4  7  3

Add one new empty column

To add a new empty column, a straightforward solution is to do

df['C'] = ''

print(df)

returns

   A  B C
0  4  8  
1  9  9  
2  1  4  
3  6  4  
4  7  3

Another example on how to add a column with zeros only:

df['D'] = 0

print(df)

returns

   A  B C  D
0  4  8    0
1  9  9    0
2  1  4    0
3  6  4    0
4  7  3    0

or a column with np.nan:

df['E'] = np.nan

print(df)

returns

   A  B C  D   E
0  4  8    0 NaN
1  9  9    0 NaN
2  1  4    0 NaN
3  6  4    0 NaN
4  7  3    0 NaN

Another approach using concat

data = np.ones((5,1))

new_col_df = pd.DataFrame(data=data,columns=['F'])

df = pd.concat([df,new_col_df], axis=1)

print(df)

returns

   A  B C  D   E    F
0  4  8    0 NaN  1.0
1  9  9    0 NaN  1.0
2  1  4    0 NaN  1.0
3  6  4    0 NaN  1.0
4  7  3    0 NaN  1.0

Add multiple empty columns

To add multiple empty columns in the same time, a solution is to use concat:

data = np.zeros((5,3))

new_col_df = pd.DataFrame(data=data,columns=['G','H','I'])

df = pd.concat([df,new_col_df], axis=1)

print(df)

returns

   A  B C  D   E    F    G    H    I
0  4  8    0 NaN  1.0  0.0  0.0  0.0
1  9  9    0 NaN  1.0  0.0  0.0  0.0
2  1  4    0 NaN  1.0  0.0  0.0  0.0
3  6  4    0 NaN  1.0  0.0  0.0  0.0
4  7  3    0 NaN  1.0  0.0  0.0  0.0

References