首页 > 解决方案 > 如何在熊猫中将多列设置为索引

问题描述

我有以下数据:

            Adj Close  year  month  day    pc_day  
Date                                               
1989-01-03   1.164242  1989      1    3       NaN  
1989-01-04   1.211100  1989      1    4  0.333333  
1989-01-05   1.218310  1989      1    5  0.250000  
1989-01-06   1.229123  1989      1    6  0.200000  
1989-01-09   1.239936  1989      1    9  0.500000  
...               ...   ...    ...  ...       ...  
2007-12-24  24.785059  2007     12   24  0.142857  
2007-12-26  24.803761  2007     12   26  0.083333  
2007-12-27  24.756376  2007     12   27  0.038462  
2007-12-28  24.913471  2007     12   28  0.037037  
2007-12-31  24.695290  2007     12   31  0.107143  

[4790 rows x 10 columns]

对于分层索引,我必须将 2 列设置为索引,Date并且month. 日期已经是日期时间的索引,但我想给它添加月份。

为此,我添加了以下代码:

data.set_index(['Date','month'], drop=False)

我收到以下错误:

KeyError: "None of ['Date'] are in the columns"

print(data.reset_index().set_index(['month','Date'], drop=False, inplace=True))按照@null 的建议使用过,但输出是none

标签: pandasdataframeindexing

解决方案


你不需要使用DataFrame.reset_index. 你只DataFrame.set_index需要append=True

data.set_index('month',append=True,inplace=True)

或者

data = data.set_index('month',append=True)

如果您以后需要交换索引,请使用DataFrame.swaplevel

data = data.set_index('month',append=True).swaplevel('Month','Date)

推荐阅读