Python Pandas | Adding new column to existing DataFrame by using Dataframe.assign()

Learn how to add a new column to existing DataFrame by using DataFrame.assign()?
Submitted by IncludeHelp, on March 29, 2022

We have already discussed how to add a column in the existing DataFrame using List as a column? and adding a column by using DataFrame.insert() method. We can also add a column by using DataFrame.assign() method, which is used to assign new columns to a DataFrame and returns a new object having the new column also. Existing columns that are re-assigned will be overwritten.

Syntax:

DataFrame.assign(**kwargs)

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

import pandas as pd

Example:

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

# Add a column course using DataFrame.insert()
dataframe1 = dataframe.assign(Course = ['B.Tech', 'MCA', 'B.E.'])
 
# Print the data after adding column
print("Data after adding column (new/updated DataFrame)...")
print(dataframe1)
print()

Output:

Data before adding column...
    Name  Age
0  Alvin   21
1   Alex   22
2  Peter   19

Data after adding column (new/updated DataFrame)...
    Name  Age  Course
0  Alvin   21  B.Tech
1   Alex   22     MCA
2  Peter   19    B.E.

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.