Q:

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

belongs to collection: Python Pandas Programs

0

Syntax:

DataFrame.insert(loc, column, value, allow_duplicates=False)

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

import pandas as pd

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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()
dataframe.insert(2, "Course", ['B.Tech', 'MCA', 'B.E.'], True)
 
# 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python Pandas | Adding new column to existing Data... >>
<< Python Pandas | Adding new column to existing Data...