Add a new column to existing DataFrame using DataFrame.insert()

Learn, how to add a new column to existing DataFrame by using DataFrame.insert()?
By IncludeHelp Last updated : April 10, 2023

DataFrame.insert() Method

We have already discussed how to add a column in the existing DataFrame using List as a column? We can also add a column by using DataFrame.insert() method, which is used to insert a column into DataFrame at the specified location.

Syntax

DataFrame.insert(loc, column, value, allow_duplicates=False)

Python program to add a new column to existing DataFrame

# Importing pandas package 
import pandas as pd 
   
# Dictionary having students data
students = {'Name':['Alvin', 'Alex', 'Peter'],
'Age':[21, 22, 19]} 
   
# Convert the dictionary into DataFrame  
dataframe = pd.DataFrame(students) 

# Print the data before adding column
print("Data before adding column...")
print(dataframe)
print()

# Add a column course using DataFrame.insert()
dataframe.insert(2, "Course", ['B.Tech', 'MCA', 'B.E.'], True)
 
# Print the data after adding column
print("Data after adding column...")
print(dataframe)
print()

Output

Data before adding column...
    Name  Age
0  Alvin   21
1   Alex   22
2  Peter   19

Data after adding column...
    Name  Age  Course
0  Alvin   21  B.Tech
1   Alex   22     MCA
2  Peter   19    B.E.

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.