How to Move a Column to First Position in Pandas DataFrame?
The basic idea to move a column in a pandas dataframe is to remove the column from its current place and insert it in the desired position. The pandas library offers many useful functions such as pop() and insert(). We will make use of these two functions to manipulate with our dataframe.
- Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop doesn’t require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly.
- item: Column name to be popped in string
Return type: Popped column in form of Pandas Series
- Pandas insert() method allows the user to insert a column in a dataframe or series(1-D Data frame).
DataFrameName.insert(loc, column, value, allow_duplicates = False)
- loc: loc is an integer which is the location of column where we want to insert new column. This will shift the existing column at that position to the right.
- Column: column is a string which is name of column to be inserted.
- Value: value is simply the value to be inserted. It can be int, string, float or anything or even series / List of values. Providing only one value will set the same value for all rows.
- Allow_duplicates : allow_duplicates is a boolean value which checks if column with same name already exists or not.
- Import module
- Create or load dataframe
- Remove the column which needs to be shifted to First Position in dataframe using pop() function.
- Insert the column at first position using insert() function.
- Print dataframe.
Let’s understand above approach by below examples:
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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course