pythonpandasdataframeindexingrename

How to get/set a pandas index column title or name?


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

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

What I'm trying to do is get/set the dataframe's 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"]

Anyone know how to do this?


Solution

  • 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
    Out[10]: 
             Column 1
    foo              
    Apples          1
    Oranges         2
    Puppies         3
    Ducks           4