Search code examples
pythonpython-3.xpandasdataframemulti-index

Python Pandas: How to set the name of MultiIndex?


My dataframe looks like below:

enter image description here

I want to set the name of red box in image as 'Ticker'. How can I do that?


Solution

  • Set index.names (plural because MultiIndex) or use rename_axis:

    df.index.names = ['Ticker','date']
    
    #if want extract second name
    df.index.names = ['Ticker',df.index.names[1]]
    

    Or:

    df = df.rename_axis(['Ticker','date'])
    
    #if want extract second name
    df = df.rename_axis(['Ticker',df.index.names[1]])
    

    Sample:

    mux = pd.MultiIndex.from_product([['NAVER'], ['2018-11-28','2018-12-01','2018-12-02']], 
                                     names=[None, 'date'])
    df = pd.DataFrame({'open':[1,2,3]}, 
                      index=mux)
    
    print(df)
                      open
          date            
    NAVER 2018-11-28     1
          2018-12-01     2
          2018-12-02     3
    
    df = df.rename_axis(['Ticker','date'])
    print (df)
                       open
    Ticker date            
    NAVER  2018-11-28     1
           2018-12-01     2
           2018-12-02     3