ADVERTISEMENT
ADVERTISEMENT

How to insert a given column at a specific position in a Pandas DataFrame?

Given a DataFrame, we have to insert a given column at a specific position.
Submitted by Pranit Sharma, on May 14, 2022

Columns are the different fields which contains their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Sometimes we might need to insert a particular column at a specific index. We can achieve this task using pandas.DataFrame.insert() method.

pandas.DataFrame.insert() Method

This method is used to insert a new column in a DataFrame manually, below is the syntax:

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

# or
DataFrame.insert(loc='', column='')

Parameter(s):

  • It takes a parameter loc which means the index where to inert the column.
  • It takes another parameter column which is used to assign a name to the new column.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example:

# Importing pandas package
import pandas as pd

# Create a dictionary for the DataFrame
dict = {
    'Name': ['Sudhir', 'Pranit', 'Ritesh','Sanskriti', 'Rani','Megha','Suman','Ranveer'],
    'Age': [16, 27, 27, 29, 29,22,19,20],
    'Marks': [40, 24, 50, 48, 33,20,29,48]
}

# Converting Dictionary to Pandas Dataframe
df = pd.DataFrame(dict)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Creating values for a new column
list = ['Pass','Fail','Pass','Pass','Pass','Fail','Fail','Pass']

# Inserting New column
df.insert(loc=3,column='Status',value=list)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output:

Example: Insert a given column at a specific position

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.