Insert a given column at a specific position in a Pandas DataFrame
Last Updated :
30 Nov, 2023
In this comprehensive guide, we will leverage the powerful DataFrame.insert()
the method provided by the Pandas library to effectively Insert a given column at a specific position in a Pandas Dataframe.
Create a Sample DataFrame
In this example below code uses Pandas to create a DataFrame named 'df' from a dictionary with columns 'col2' and 'col3' and their respective values. The data frame is then displayed.
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:
col2 col3
0 6 11
1 7 12
2 8 13
3 9 14
4 10 15
Ways to Add a column in Pandas DataFrame
There are various ways to Insert a given column at a specific position in a Pandas Dataframe. In this article, we will explain some commonly used methods.
- Add Column to Dataframe
- Insert a column at the beginning
- Insert a column at specific position
- Insert a column at the end
- Using
assign()
method - Using insert() method
Pandas Add Column to Dataframe
Here we are adding a new column in the dataframe and then define a list in the same order in which we want to get the columns.
Python3
# adding a new column
df['col1']=0
# show the dataframe
df = df[list(('col1','col2','col3'))]
# show the dataframe
df
Output:
col1 col2 col3
0 0 6 11
1 0 7 12
2 0 8 13
3 0 9 14
4 0 10 15
Insert a column at the beginning of the dataframe using insert() Method
In this example, we are using an insert() method to Insert a column at the beginning of the Dataframe.
Python3
# 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:Â
col1 col2 col3
0 1 6 11
1 2 7 12
2 3 8 13
3 4 9 14
4 5 10 15
Insert a column at the end in a Dataframe using Loc() Method
In this example, we are using the Pandas loc
method, a new column named 'New_Column' is added with specified values, and the modified DataFrame is displayed.
Python3
# Using loc method
df.loc[:, 'New_Column'] = [20, 30, 40, 50, 60]
# Displaying the modified DataFrame
print(df)
Output:
col2 col3 New_Column
0 6 11 20
1 7 12 30
2 8 13 40
3 9 14 50
4 10 15 60
Insert a column at the specific position of the dataframe
In this example, the below code inserts a new column ('New_Column') into an existing DataFrame (df
) at a specified position and displays the resulting modified data frame.
Python3
# Creating a new DataFrame
new_df = pd.DataFrame({'New_Column': [20, 30, 40, 50, 60]})
df = pd.concat([df.iloc[:, :1], new_df, df.iloc[:, 1:]], axis=1)
# Displaying the modified DataFrame
print(df)
Output :
col2 New_Column col3
0 6 20 11
1 7 30 12
2 8 40 13
3 9 50 14
4 10 60 15
Insert a column in a Dataframe using assign()
method
In this example below code employs the Pandas assign
method to add a new column named 'New_Column' with specified values to the DataFrame 'df'. The modified data frame is then displayed.
Python3
# Using assign method
df = df.assign(New_Column=[20, 30, 40, 50, 60])
# Displaying the modified DataFrame
print(df)
Output :
col2 col3 New_Column
0 6 11 20
1 7 12 30
2 8 13 40
3 9 14 50
4 10 15 60
Insert a column in a Dataframe using insert
() method
In this example below code utilizes the Pandas `insert` method to add a new column named 'New_Column' at position 1 in the DataFrame, using values from a Pandas Series. The modified data frame is then displayed.
Python3
# Using insert with a Series
df.insert(1, 'New_Column', pd.Series([20, 30, 40, 50, 60]))
# Displaying the modified DataFrame
print(df)
Output :
col2 New_Column col3
0 6 20 11
1 7 30 12
2 8 40 13
3 9 50 14
4 10 60 15
Similar Reads
Insert row at given position in Pandas Dataframe
Inserting a row in Pandas DataFrame is a very straight forward process and we have already discussed approaches in how insert rows at the start of the Dataframe. Now, let's discuss the ways in which we can insert a row at any position in the dataframe having integer based index.Solution #1 : There d
3 min read
Get a List of a Specific Column of a Pandas DataFrame
In data analysis, extracting specific columns from a DataFrame and converting them into Python lists is a common requirement. Pandas provides multiple ways to achieve this efficiently. This article explores various methods to extract a specific column from a Pandas DataFrame and convert it into a li
3 min read
Split a column in Pandas dataframe and get part of it
When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement. We can use Pandas .str accessor, it does fast vectorized string operations for Series and Dataframes and returns a string object. Pandas str accessor has nu
2 min read
Get a specific row in a given Pandas DataFrame
In the Pandas Dataframe, we can find the specified row value with the function iloc(). In this function, we pass the row number as a parameter. The core idea behind this is simple: you access the rows by using their index or position. In this article, we'll explore different ways to get a row from a
5 min read
How to Move a Column to First Position in Pandas DataFrame?
Moving a column to the first position in a Pandas DataFrame means changing the column order so that the column you want appears first. For example, if you have a DataFrame with columns ['Age', 'Name', 'City'] and you want to move the 'Name' column to the front, the result will be ['Name', 'Age', 'Ci
3 min read
Change the order of a Pandas DataFrame columns in Python
Let's explore ways to change the order of the Pandas DataFrame column in Python. Reordering columns in large Pandas DataFrames enhances data readability and usability.Change the Order of Pandas DataFrame Columns using ilociloc method allows you to reorder columns by specifying the index positions of
2 min read
Apply a function to each row or column in Dataframe using pandas.apply()
Let's explore how to use the apply() function to perform operations on Pandas DataFrame rows and columns.pandas.DataFrame.apply() method is used to apply a function along the axis of a DataFrame (either rows or columns). Syntax: DataFrame.apply(func, axis=0, raw=False, result_type=None, args=None, *
5 min read
How to Access a Column in a DataFrame with Pandas
In this article we will explore various techniques to access a column in a dataframe with pandas with concise explanations and practical examples.Method 1: Accessing a Single Column Using Bracket NotationBracket notation is the most straightforward method to access a column. Use the syntax df['colum
4 min read
Add column names to dataframe in Pandas
Sometimes, Pandas DataFrames are created without column names, or with generic default names (like 0, 1, 2, etc.). Let's learn how to add column names to DataFrames in Pandas. Adding Column Names Directly to columns Attribute The simplest way to add column names is by directly assigning a list of co
3 min read
Adding New Column to Existing DataFrame in Pandas
Adding a new column to a DataFrame in Pandas is a simple and common operation when working with data in Python. You can quickly create new columns by directly assigning values to them. Let's discuss how to add new columns to the existing DataFrame in Pandas. There can be multiple methods, based on d
6 min read