Skip to content
Related Articles

Related Articles

Add a new column in Pandas Data Frame Using a Dictionary

Improve Article
Save Article
  • Last Updated : 09 Nov, 2018
Improve Article
Save Article


Pandas is basically the library in Python used for Data Analysis and Manipulation. To add a new Column in the data frame we have a variety of methods. But here in this post, we are discussing adding a new column by using the dictionary.

Let’s take Example!




# Python program to illustrate
# Add a new column  in Pandas 
  
# Importing the pandas Library
import pandas as pd
  
# creating a data frame with some data values.
data_frame = pd.DataFrame([[i] for i in range(7)], columns =['data'])
  
print (data_frame)

Output:

  data 
0  0
1  1
2  2
3  3
4  4
5  5
6  6

Now Using the above-written method lets try to add a new column to it. Let’s add the New columns named as “new_data_1”.
Map Function : Adding column “new_data_1” by giving the functionality of getting week name for the column named “data”. Call map and pass the dict, this will perform a lookup and return the associated value for that key.

Let’s Introduce variable week data typed as Dictionary that includes the name of days in the week.




# Python program to illustrate
# Add a new column  in Pandas 
# Data Frame Using a Dictionary
  
import pandas as pd
  
data_frame = pd.DataFrame([[i] for i in range(7)], columns =['data'])
  
# Introducing weeks as dictionary
weeks = {0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday'
4:'Thursday', 5:'Friday', 6:'Saturday'}
  
# Mapping the dictionary keys to the data frame.
data_frame['new_data_1'] = data_frame['data'].map(weeks)
print (data_frame)

Output:

  data  new_data_1
0  0  Sunday
1  1  Monday
2  2  Tuesday
3  3  Wednesday
4  4  Thursday
5  5  Friday
6  6  Saturday

And, we have successfully added a column (Sunday, Monday….) at the end.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!