Get column index from column name in Python pandas

Given a DataFrame, we have to get column index from column name.
Submitted by Pranit Sharma, on May 09, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. In a DataFrame, both rows and columns are assigned with an index value ranging from 0 to n-1. 0th is the first row and n-1th index is the last row. On the other hand, columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both rows & column values. Here, we are going to learn how to get the index number of a column.

Pandas allow us to achieve this task using DataFrame.columns.get_loc() method.

This method takes the name of the column as a parameter and returns the corresponding index number.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example:

# Importing pandas package
import pandas as pd

# Defining a DataFrames
df = pd.DataFrame(data = {'Parle':['Frooti','Krack-jack','Hide&seek'],
                           'Dabur':['Chawanprash','Honey','Hair oil']})

# Display DataFrame
print("Original DataFrame:\n",df,"\n")

# Getting index number of "Nestle" column
result = df.columns.get_loc('Nestle')

# Display Result
print("The index number of the column 'Nestle' is:\n",result)


Example 1: Get column index from column name

Python Pandas Programs »



Comments and Discussions!





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.