In this post, we will learn how to move a single column in a Pandas Dataframe to the first position in Pandas Dataframe. The basic idea is to remove the column/variable from the dataframe using Pandas pop() function and using Pandas insert() function to put it in the first position of Pandas dataframe.
Let us load pandas and numpy.
import pandas as pd import numpy as np pd.__version__
We will generate some data using NumPy’s random module and store it in a Pandas dataframe. Unlike before, here we create a Pandas dataframe using two-dimensional NumPy array of size 8×3 and specify column names for the dataframe with the argument “columns”.
np.random.seed(42) df =pd.DataFrame(np.random.randint(20, size=(8,3)), columns=list('BCA'))
Let us get a look at the top 5 rows of the dataframe with Pandas head() function.
df.head() B C A 0 6 19 14 1 10 7 6 2 18 10 10 3 3 7 2 4 1 11 5
We can see that columns in the data frame are out of order and we would like to move the third column A to the first position of the dataframe.
To move a column to first column in Pandas dataframe, we first use Pandas pop() function and remove the column from the data frame.
Here we remove column “A” from the dataframe and save it in a variable.
col_name="A" first_col = df.pop(col_name)
first_col 0 14 1 6 2 10 3 2 4 5 5 11 6 9 7 14 Name: A, dtype: int64
Now original datafram does not contain the variable that we wanted to move to the first column.
df.head() B C 0 6 19 1 10 7 2 18 10 3 3 7 4 1 11
Now we can use Pandas insert() function and insert the opped column into first position of the dataframe. The first argument of insert() function is the location we want to insert, here it is 0.
df.insert(0, col_name, first_col)
Now we have moved the column of interest to first column in Pandas data frame.
df.head() A B C 0 14 6 19 1 6 10 7 2 10 18 10 3 2 3 7 4 5 1 11
[…] a column is to use two dataframe with common ID and merge them. One of the common applications of Pandas insert() function is to move a column to the front of the […]