Skip to content
Related Articles

Related Articles

Insert a given column at a specific position in a Pandas DataFrame
  • Last Updated : 26 Jul, 2020
GeeksforGeeks - Summer Carnival Banner

In this article, we will use Dataframe.insert() method of Pandas to insert a new column at a specific column index in a dataframe.

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

Return: None

Code: Let’s create a Dataframe.

Python3






# Importing pandas library
import pandas as pd
  
# dictionary
values = {'col2': [6, 7, 8
                   9, 10],
          'col3': [11, 12, 13,
                   14, 15]}
  
# Creating dataframe
df = pd.DataFrame(values)
  
# show the dataframe
df

Output:

Dataframe

Example 1: Inserting column at the beginning of the dataframe.

Python3




# Importing pandas library
import pandas as pd
  
# dictionary
values = {'col2': [6, 7, 8
                   9, 10], 
          'col3': [11, 12, 13,
                   14, 15]}
  
# Creating dataframe
df = pd.DataFrame(values)
  
# New column to be added
new_col = [1, 2, 3, 4, 5
  
# Inserting the column at the
# beginning in the DataFrame
df.insert(loc = 0,
          column = 'col1',
          value = new_col)
# show the dataframe
df

Output: 

Insert new column at beginning of the dataframe

Example 2: Inserting column in the middle of the dataframe

Python3






# Importing pandas library
import pandas as pd
  
# dictionary
values = {'col2': [6, 7, 8
                   9, 10], 
          'col3': [11, 12, 13,
                   14, 15]}
  
# Creating dataframe
df = pd.DataFrame(values)
  
# New column to be added
new_col = [1, 2, 3, 4, 5
  
# Inserting the column at the
# middle of the DataFrame
df.insert(loc = 1,
          column = 'col1',
          value = new_col)
# show the dataframe
df

Output: 

Insert new column at middle of the dataframe

Example 3: Inserting column at the end of the dataframe

Python3




# Importing pandas library
import pandas as pd
  
# dictionary
values = {'col2': [6, 7, 8
                   9, 10], 
          'col3': [11, 12, 13,
                   14, 15]}
  
# Creating dataframe
df = pd.DataFrame(values)
  
# New column to be added
new_col = [1, 2, 3, 4, 5
  
# Inserting the column at the
# end of the DataFrame
# df.columns gives index array 
# of column names
df.insert(loc = len(df.columns),
          column = 'col1',
          value = new_col)
# show the dataframe
df

Output:  

Insert new column at end of the dataframe

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :