Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add new column in Pandas Data Frame Using a Dictionary
A Pandas DataFrame is a two-dimensional tabular data structure with rows and columns. You can add a new column by mapping values from a Python dictionary to an existing column using the map() function.
Creating a DataFrame
First, create a DataFrame from a Pandas Series ?
import pandas as pd s = pd.Series([6, 8, 3, 1, 12]) df = pd.DataFrame(s, columns=['Month_No']) print(df)
Month_No 0 6 1 8 2 3 3 1 4 12
Adding a Column Using a Dictionary
Create a dictionary that maps month numbers to names, then use map() to add a new column ?
import pandas as pd
s = pd.Series([6, 8, 3, 1, 12])
df = pd.DataFrame(s, columns=['Month_No'])
# Dictionary mapping month numbers to names
months = {6: 'Jun', 8: 'Aug', 3: 'Mar', 1: 'Jan', 12: 'Dec'}
# Add new column using map()
df['Month_Name'] = df['Month_No'].map(months)
print(df)
Month_No Month_Name 0 6 Jun 1 8 Aug 2 3 Mar 3 1 Jan 4 12 Dec
The map() function looks up each value in Month_No against the dictionary keys and fills the new column with the corresponding values. If a key is not found, NaN is inserted.
Other Methods to Add Columns
Using assign()
Returns a new DataFrame with the added column (does not modify original) ?
import pandas as pd
df = pd.DataFrame({'Month_No': [6, 8, 3, 1, 12]})
months = {6: 'Jun', 8: 'Aug', 3: 'Mar', 1: 'Jan', 12: 'Dec'}
df_new = df.assign(Month_Name=df['Month_No'].map(months))
print(df_new)
Month_No Month_Name 0 6 Jun 1 8 Aug 2 3 Mar 3 1 Jan 4 12 Dec
Using insert() at a Specific Position
Insert the new column at a specific index position ?
import pandas as pd
df = pd.DataFrame({'Month_No': [6, 8, 3, 1, 12]})
months = {6: 'Jun', 8: 'Aug', 3: 'Mar', 1: 'Jan', 12: 'Dec'}
# Insert at position 0 (first column)
df.insert(0, 'Month_Name', df['Month_No'].map(months))
print(df)
Month_Name Month_No 0 Jun 6 1 Aug 8 2 Mar 3 3 Jan 1 4 Dec 12
Summary
| Method | Modifies Original? | Choose Position? |
|---|---|---|
df['col'] = df['key'].map(dict) |
Yes | No (appends at end) |
df.assign(col=...) |
No (returns new df) | No |
df.insert(pos, 'col', ...) |
Yes | Yes |
Conclusion
Use map() with a dictionary to add a new column by mapping values from an existing column. Use assign() for immutable operations or insert() to place the new column at a specific position. If a dictionary key is missing for any row, NaN is automatically inserted.
