user3595632
user3595632

Reputation: 5730

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?

Upvotes: 26

Views: 27039

Answers (2)

cottontail
cottontail

Reputation: 23051

If you want to only set the name of a MultiIndex level by position, you can do so using set_names. To set the name of the first level to 'Ticker', you can use the following:

df.index = df.index.set_names('Ticker', level=0)

Can set it in-place as well:

df.index.set_names('Ticker', level=0, inplace=True)

This is useful if the MultiIndex has a lot of levels and you only want to set/modify the name of one/few levels.

A working example:

mi = pd.MultiIndex.from_product([['AMZN'], ['2023-11-28', '2023-12-01', '2023-12-02']], names=[None, 'date'])
df = pd.DataFrame({'open':[1, 2, 3]}, index=mi)
df.index.set_names('Ticker', level=0, inplace=True)  # change first level name

The last line makes the following transformation:

output


N.B. Also works for MultiIndex columns as well. For columns, instead of .index, use .columns. So for example, for a dataframe with a MultiIndex columns, if we want to change the names of first and second levels, we can use the following:

df.columns.set_names(["first", "second"], level=[0,1], inplace=True)

Upvotes: 0

jezrael
jezrael

Reputation: 862511

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

Upvotes: 38

Related Questions