Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: How to set the name of multiindex?

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?

like image 698
user3595632 Avatar asked Mar 27 '18 05:03

user3595632


People also ask

How do I rename a MultiIndex in pandas?

To rename the multi index columns of the pandas dataframe, you need to use the set_levels() method. Use the below snippet to rename the multi level columns. where, ['b1','c1','d1'] - New column names of the index.

Can you name the index column in pandas?

You can use the rename() method of pandas. DataFrame to change column/index name individually. Specify the original name and the new name in dict like {original name: new name} to columns / index parameter of rename() . columns is for the column name, and index is for the index name.

Can you assign a name to the index of pandas series?

Pandas Series: rename() functionThe rename() function is used to alter Series index labels or name.

How do you use MultiIndex in pandas?

Creating a MultiIndex (hierarchical index) object A MultiIndex can be created from a list of arrays (using MultiIndex. from_arrays() ), an array of tuples (using MultiIndex. from_tuples() ), a crossed set of iterables (using MultiIndex. from_product() ), or a DataFrame (using MultiIndex.


1 Answers

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
like image 66
jezrael Avatar answered Sep 19 '22 12:09

jezrael