Home »
Python »
Python Programs
Retrieve name of column from its index in pandas
Given a pandas dataframe, we have to retrieve name of column from its index.
By Pranit Sharma Last updated : October 03, 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
We are given a pandas DataFrame with a NumPy array of values of that DataFrame. We have the index of the specific column and we already have the row of an Important value. We need to get the column name for that particular value from this DataFrame.
Retrieving the name of column from its index in pandas
For this purpose, we will first define a variable that will store the specific value that which column we want. We will then find the values of that column by passing these values inside pandas.DataFrame.columns() method as an index.
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 dictionary
d = {
'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]
}
# CreatingDataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original DataFrame:\n",df,"\n")
# defining index
ind = 3
# Finding column values
values = df.columns[ind]
# Display result
print("Result:\n", values)
Output
The output of the above program is:
Python Pandas Programs »