Pandas Get Column Name by Index or Position

Sometimes you may have a column index and want to get column name by index in pandas DataFrmae, you can do so by using DataFrame.columns[idx]. Note that the index starts from 0.

Get Column Name by Index Example

DataFrame.columns returns an object of pandas.core.indexes.base.Index and use the position by using [] operator to get the column name by index or position.

Let’s see with an example by creating a DataFrame.


import pandas as pd
import numpy as np
technologies = {
    'Courses':["Spark","PySpark","Python"],
    'Fee' :[20000,25000,22000],
    'Duration':['30days','40days','35days'],
    'Discount':[1000,2300,1200]
              }
df = pd.DataFrame(technologies)
print(df)

Now let’s get the column names from pandas DataFrame, As I said the below example returns an Index object containing all column names.


# Get Column Name by Index Example
print(df.columns)

# Output:
# Index(['Courses', 'Fee', 'Duration', 'Discount'],
# dtype='object')

to get column name by column index use t


print(df.columns[2])

# Output:
# Duration

Naveen (NNK)

I am Naveen (NNK) working as a Principal Engineer. I am a seasoned Apache Spark Engineer with a passion for harnessing the power of big data and distributed computing to drive innovation and deliver data-driven insights. I love to design, optimize, and managing Apache Spark-based solutions that transform raw data into actionable intelligence. I am also passion about sharing my knowledge in Apache Spark, Hive, PySpark, R etc.

Leave a Reply

You are currently viewing Pandas Get Column Name by Index or Position