Python Pandas: How to set the name of multiindex?

user3595632 picture user3595632 · Mar 27, 2018 · Viewed 9.9k times · Source

enter image description here

I want to add the name of index of multi-index dataframe.

I want to set the name of red box in image as 'Ticker'

How can I do that?

Answer

jezrael picture jezrael · Mar 27, 2018

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