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]}) df
# new column C = [7, 8, 9] df.insert(loc=0, column= 'MyNew', value = C ) df
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 ) df
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
df.columns.get_loc('MySecond')
2
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 ) df
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 ) df