Pandas Get Column Name by Index or Position

Sometimes you may have an column index and wanted to get column name by index in pandas DataFrmae, you can do so by using DataFrame.columns[idx]. Note that index start 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.


print(df.columns)
# Outputs
Index(['Courses', 'Fee', 'Duration', 'Discount'], dtype='object')

to get column name by column index use t


print(df.columns[2])

# Outputs
Duration

pandas column by index

NNK

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

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