- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- How to add a new column to a data frame using mutate in R?
- How to add a new column in an R data frame with count based on factor column?
- How to add a new column at the front of an existing R data frame?
- How to add a new column to represent the percentage for groups in an R data frame?
- How to add a new column to an R data frame with largest value in each row?
- How to add a new column in an R data frame by combining two columns with a special character?
- Python - Add a new column with constant value to Pandas DataFrame
- How to concatenate column values and create a new column in an R data frame?
- Add a new value to a column of data type enum in MySQL?
- How to add a rank column in base R of a data frame?
- How to add a column in an R data frame with consecutive numbers?
- How to add a column between columns or after last column in an R data frame?
- How to add new keys to a dictionary in Python?
- How to match a column in a data frame with a column in another data frame in R?
- How to create a new column in an R data frame based on some condition of another column?
