Add new column in Pandas Data Frame Using a Dictionary



Pandas Data Frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. It can be created using python dict, list, and series etc. In this article, we will see how to add a new column to an existing data frame.

So first let's create a data frame using pandas series. In the below example we are converting a pandas series to a Data Frame of one column, giving it a column name Month_no.

Example

import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) print (df)

Output

Running the above code gives us the following result −

   Month_No 0           6 1           8 2           3 3           1 4         12

Next we create a new python dictionary containing the month names with values from the pandas series as the indices of the dictionary. Then we use a map function to add the month's dictionary with the existing Data Frame to get a new column. The map function takes care of arranging the month names with the indices of the dictionary.

Example

import pandas as pd s = pd.Series([6,8,3,1,12]) df = pd.DataFrame(s,columns=['Month_No']) months = {6:'Jun', 8:'Aug', 3:'Mar', 1:'Jan',12:'Dec'} df['Month_Name'] = df['Month_No'].map(months) print (df)

Output

Running the above code gives us the following result −

   Month_No Month_Name 0        6         Jun 1        8         Aug 2        3         Mar 3        1         Jan 4        12       Dec
Updated on: 2020-06-30T08:46:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements