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
Related Topics
- Creating an empty Pandas DataFrame
- How to Check if a Pandas DataFrame is Empty
- How to check if a column exists in Pandas Dataframe
- How to delete column from pandas DataFrame
- How to select multiple columns from Pandas DataFrame
- Selecting multiple columns in a Pandas dataframe based on condition
- Selecting rows in pandas DataFrame based on conditions
- How to Drop rows in DataFrame by conditions on column values
- Rename column in Pandas DataFrame
- Get a List of all Column Names in Pandas DataFrame
- Change the order of columns in Pandas dataframe
- Concatenate two columns into a single column in pandas dataframe
- How to count the number of rows and columns in a Pandas DataFrame
- Use a list of values to select rows from a pandas dataframe
- How to iterate over rows in a DataFrame in Pandas
- How to drop rows/columns of Pandas DataFrame whose value is NaN
- How to Export Pandas DataFrame to a CSV File
- Convert list of dictionaries to a pandas DataFrame
- How to set a particular cell value in pandas DataFrame