Insert a new column in existing DataFrame

A pandas dataframe is implemented as an ordered dict of columns. In this article, you will get to know how to add a new column to an existing data frame. So first let's create a data frame with values.
import pandas as pd import numpy as np df = pd.DataFrame() df['Name'] = ['John', 'Doe', 'Bill','Jim','Harry','Ben'] df['TotalMarks'] = [82, 38, 63,22,55,40] df['Grade'] = ['A', 'E', 'B','E','C','D'] df['Promoted'] = [True, False,True,False,True,True] df
Name TotalMarks Grade Promoted 0 John 82 A True 1 Doe 38 E False 2 Bill 63 B True 3 Jim 22 E False 4 Harry 55 C True 5 Ben 40 D True

Using [] accessor

df['Age'] = [12, 12, 13, 12, 13, 12] #Adding column 'Age' df
Name TotalMarks Grade Promoted Age 0 John 82 A True 12 1 Doe 38 E False 12 2 Bill 63 B True 13 3 Jim 22 E False 12 4 Harry 55 C True 13 5 Ben 40 D True 12
Here, when you use the [] to pandas DataFrame is quietly performing an outer join or outer merge using the index of the left hand dataframe and the index of the right hand series. df['column'] = series.

Using insert() method

df.insert(loc, column, value)
You can inset a column to pandas DataFrmae at a specified index using insert() method.
df.insert(1,"Age",[12, 12, 13, 12, 13, 12]) df
Name Age TotalMarks Grade Promoted 0 John 12 82 A True 1 Doe 12 38 E False 2 Bill 13 63 B True 3 Jim 12 22 E False 4 Harry 13 55 C True 5 Ben 12 40 D True
Here you can see the column 'Age' inserted at the index position of 1 using insert() method.

Using assign() method

Pandas DataFrame has an assign() function that allows you to create a new dataframe with new column added to the old dataframe.
new_df = df.assign(Age = [12, 12, 13, 12, 13, 12]) new_df
Name TotalMarks Grade Promoted Age 0 John 82 A True 12 1 Doe 38 E False 12 2 Bill 63 B True 13 3 Jim 22 E False 12 4 Harry 55 C True 13 5 Ben 40 D True 12