Home »
Python »
Python Programs
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:
Python Pandas Programs »
ADVERTISEMENT
ADVERTISEMENT