Q:

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

belongs to collection: Python Pandas Programs

0

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

All Answers

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

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

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
How to update a DataFrame in pandas while iteratin... >>
<< How to convert floats to ints in Pandas?...