Python Pandas:如何设置多索引的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49505080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:22:13  来源:igfitidea点击:

Python Pandas: How to set the name of multiindex?

pythonpandasmulti-index

提问by user3595632

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'

我想将图像中红框的名称设置为“Ticker”

How can I do that?

我怎样才能做到这一点?

回答by jezrael

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

设置index.names(复数因为MultiIndex)或使用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