Radical Edward Radical Edward - 11 months ago 102
Python Question

Pandas index column title or name

Does anyone know how to get the index column name in pandas? Here's an example dataframe of what I'm talking about:

Column 1
Index Title
Apples 1
Oranges 2
Puppies 3
Ducks 4

What I'm trying to do is get/set the index title. The only way I can figure out how to set the title is by adding a column in the dataframe, giving that column a name, then setting the index to be that column and deleting the added column. By default the index title becomes that columns title but after I delete it I have no way of getting that title again. Here's a working example:

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

Anyone know how to do this? I was unable to find anything about this online. Thanks!

Answer Source

You can just get/set the index via its name property

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
         Column 1
Apples          1
Oranges         2
Puppies         3
Ducks           4