Add a new column to existing DataFrame using a dictionary

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

We have already discussed,

Add a new column to DataFrame using dictionary

We can also add a column by using a dictionary. In this method – use an existing column as the key and their respective values will be the values for a new column.


dataframe['column_name'] = dictionary

To work with MultiIndex in Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Python program to add a new column to existing DataFrame using a dictionary

# 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...")

# Dictionary with key value from an existing DataFrame
# and, values of the new column to be added
address = {'':'Alvin', 'MCA':'Alvin', 'B.E.':'Peter'}

# Add the Dictionary to the DataFrame
dataframe['Course'] = address
# Print the data after adding column
print("Data after adding column ...")


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
1   Alex   22     MCA
2  Peter   19    B.E.

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.