Add a new column to existing DataFrame by declaring a new list as a column in Python Pandas

Learn, how to add a new column to existing DataFrame by declaring a new list as a column? By IncludeHelp Last updated : April 10, 2023

How to add a new column to existing DataFrame?

To add a new column in the DataFrame, we will create a list as a column and then, the list can be assigned to the DataFrame.

List as a column

list_name = [values]

Adding List as a column to DataFrame

dataframe['column_name'] = list_name

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

import pandas as pd

Python program to add a new column to existing DataFrame by declaring a new list as a column

# 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()

# List as column
course = ['B.Tech', 'MCA', 'B.E']
 
# Add a new column by list
dataframe['Course'] = course
 
# Print the data after adding column
print("Data after adding column...")
print(dataframe)
print()

Output

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

Data after adding column...
    Name  Age  Course
0  Alvin   21  B.Tech
1   Alex   22     MCA
2  Peter   19     B.E

Python Pandas Programs »

All Python Pandas Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.