
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Move a column to the first position in Pandas DataFrame?
Use pop() to pop the column and insert it using the insert() methodi.e. moving a column. At first, create a DataFrame with 3 columns −
dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } )
Move column "Roll Number" to 1st position by first popping the column out −
shiftPos = dataFrame.pop("Roll Number")
Insert column on the 1st position −
dataFrame.insert(0, "Roll Number", shiftPos)
Example
Following is the code −
import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],"Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } ) print"DataFrame ...\n",dataFrame # move column "Roll Number" to 1st position shiftPos = dataFrame.pop("Roll Number") # insert column on the 1st position dataFrame.insert(0, "Roll Number", shiftPos) print"\nUpdated DataFrame after moving a column to the first position...\n",dataFrame
Output
This will produce the following output −
DataFrame ... Result Roll Number Student 0 Pass 5 Jack 1 Fail 10 Robin 2 Pass 3 Ted 3 Fail 8 Marc 4 Pass 2 Scarlett 5 Pass 9 Kat 6 Pass 6 John Updated DataFrame after moving a column to the first position... Roll Number Result Student 0 5 Pass Jack 1 10 Fail Robin 2 3 Pass Ted 3 8 Fail Marc 4 2 Pass Scarlett 5 9 Pass Kat 6 6 Pass John
- Related Articles
- Capitalize first letter of a column in Pandas dataframe
- Pandas dataframe capitalize first letter of a column
- How to move a column from other position to first position in an R data frame?
- Python - Add a zero column to Pandas DataFrame
- Apply uppercase to a column in Pandas dataframe in Python
- Python – Create a new column in a Pandas dataframe
- Python Pandas – Display all the column names in a DataFrame
- Python - Add a prefix to column names in a Pandas DataFrame
- Adding a new column to existing DataFrame in Pandas in Python
- Python - How to select a column from a Pandas DataFrame
- Python - Calculate the variance of a column in a Pandas DataFrame
- Adding a new column to an existing DataFrame in Python Pandas
- Python - Stacking a multi-level column in a Pandas DataFrame
- Python - How to Count the NaN Occurrences in a Column in Pandas Dataframe?
- How to count the NaN values in a column in a Python Pandas DataFrame?

Advertisements