Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (11.4k points)

How do I get the index column name in python pandas? Here's an example dataframe:

Index Title  Column 1 

Apples         1 

Oranges      2 

Puppies       3  

Ducks          4

What I'm trying to do is get/set the dataframe index title. Here is what I tried:

import pandas as pd 

data = {'Column 1' : [1., 2., 3., 4.], 

'Index Title' : ["Apples", "Oranges", "Puppies", "Ducks"]} 

df = pd.DataFrame(data) 

df.index = df["Index Title"] 

del df["Index Title"] 

print(df)

Does anyone know how to do this?

1 Answer

0 votes
by (33.1k points)

Use Pandas dataframe.index.name method:

In [7]: df.index.name 

Out[7]: 

'Index Title' 

In [8]: df.index.name = 'foo' 

In [9]: df.index.name 

Out[9]: 

'foo' 

In [10]: df 

Out[10]: 

foo   Column 1 

Apples     1 

Oranges  2 

Puppies   3 

Ducks      4

Related questions

Browse Categories

...