Q:

Get column index from column name in Python pandas

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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'],
                           'Nestle':['Maggie','Kitkat','EveryDay'],
                           '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)

Output:

Example 1: Get column index from column name

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to keep only date part when using pandas.to_da... >>
<< Pandas: Drop a level from a multi-level column ind...