Predictive Hacks

How to Add Columns to Pandas at a Specific Location

In Pandas, when we add a new column, it appears at the end of the data frame. However, in many times there is a need to add a column at a specific location. Let’s see how we can do it in Pandas by using the insert method.

Insert a Pandas column at the beginning

Let’s see how we can add a column at the beginning of the data frame.

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# new column
C = [7, 8, 9]

df.insert(loc=0, column= 'MyNew', value = C )


Add a Column at a Specific Location

In the next example, we show how to add a new column at a specific location, and more particularly as the third column.

# new column
D = [10, 11, 12]

df.insert(loc=2, column= 'MySecond', value = D )


Add a Column After or Before a Column Name

Finally, let’s say that we want to add a new column after a specific column. For example, assume that we want to add a new column after the MySecond column. As we explained before, we need to specify the location of the column that we want to add. In Pandas, we can get the location of the column by column name using the get_loc method. The following example is helpful to understand.

Get the location of the MySecond Column


Add the new column after the MySecond Column

Since we got the location of the reference column, we can specify the location of the new column. For example, the location of the new column will be df.columns.get_loc('MySecond') + 1 = 3

# new column
E = [13, 14, 15]

df.insert(loc=df.columns.get_loc('MySecond')+1, column= 'MyThird', value = E )


Add the new column before the MySecond Column

Similarly, we can add a new column before a specific column.

# new column
F = [16, 17, 18]

df.insert(loc=df.columns.get_loc('MySecond'), column= 'MyForth', value = F )


Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s