我有以下数据:
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"
我已按照@null的建议使用print(data.reset_index().set_index(['month','Date'], drop=False, inplace=True))
,但输出为none
答案 0 :(得分:1)
您不需要使用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)
答案 1 :(得分:0)
如文档中的here所定义。 set_index
方法将键作为参数,其中
键:类似标签或数组的标签或标签/数组的列表 此参数可以是单个列键,长度与调用DataFrame相同的单个数组,也可以是包含列键和数组的任意组合的列表。在这里,“数组”包含Series,Index,np.ndarray和Iterator的实例。
因此它必须是列名或列名列表。
只需尝试:
data.reset_index().set_index(['Date', 'month'], drop=False, inplace=True)
答案 2 :(得分:0)
从数据“日期”开始,未设置为索引
要为您的数据设置多索引数据框:
data['Date'] = pd.to_datetime(data['Date'])
data.set_index(['Date', 'month'], inplace=True)
你应该得到
Adj Close year day pc_day
Date month
1989-01-03 1 1.164242 1989 3 0.000000
1989-01-04 1 1.211100 1989 4 0.333333
1989-01-05 1 1.218310 1989 5 0.250000
1989-01-06 1 1.229123 1989 6 0.200000
1989-01-09 1 1.239936 1989 9 0.500000
2007-12-24 12 24.785059 2007 24 0.142857
2007-12-26 12 24.803761 2007 26 0.083333
2007-12-27 12 24.756376 2007 27 0.038462
2007-12-28 12 24.913471 2007 28 0.037037
2007-12-31 12 24.695290 2007 31 0.107143
,索引显示为
data.index
应该返回
MultiIndex([('1989-01-03', 1),
('1989-01-04', 1),
('1989-01-05', 1),
('1989-01-06', 1),
('1989-01-09', 1),
('2007-12-24', 12),
('2007-12-26', 12),
('2007-12-27', 12),
('2007-12-28', 12),
('2007-12-31', 12)],
names=['Date', 'month'])