How to retrieve name of column from its index in Pandas?

Learn, how to retrieve name of column from its index in Python Pandas? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose that we are given a pandas dataframe and a numpy array of values of that dataframe. We also have the index of a specific column and we already have the row index of an important value.

Retrieving name of column from its index in Pandas

We need to get the column name of that particular value from our dataframe.

There is a very simple approach for this purpose, we just need the position with the help of which we can retrieve the name of the column.

Let us understand with the help of an example,

Python program to retrieve name of column from its index in Pandas

# Importing pandas package
import pandas as pd

# Creating a dataframe
df = pd.DataFrame({'Harry':[1,2,3],'Bob':[4,5,6],'Chiku':[7,8,9],'Denver':[10,11,12],'Esha':[13,14,15]})

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

# Defining a position
pos = 4

# Finding column name
name = df.columns[pos]

# Display result
print("Name of column:\n",name)

Output

The output of the above program is:

Example: How to retrieve name of column from its index in Pandas?

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.