How to add a column to a pandas DataFrame in python ?

Published: April 11, 2020

Tags: Pandas; python;

DMCA.com Protection Status

Example of how to add a column to a pandas DataFrame in python:

Create a simple dataframe with pandas

Let's start by creating a simple dataframe df:

>>> import pandas as pd
>>> import numpy as np
>>> data = np.arange(1,13)
>>> data = data.reshape(3,4)
>>> df = pd.DataFrame(data=data,columns=['a','b','c','d'])
>>> df
   a   b   c   d
0  1   2   3   4
1  5   6   7   8
2  9  10  11  12

Add a column to a dataframe dataframe

To add a column we can simply do like this:

>>> df['e'] = [30,40,50]
>>> df
   a   b   c   d   e
0  1   2   3   4  30
1  5   6   7   8  40
2  9  10  11  12  50

or other option use the function concat():

>>> df_new_column = pd.DataFrame([[60],[70],[80]], columns=['f'] )
>>> df_new_column
    f
0  60
1  70
2  80
>>> df = pd.concat([df,df_new_column], axis=1)
>>> df
   a   b   c   d   f
0  1   2   3   4  60
1  5   6   7   8  70
2  9  10  11  12  80

References