pandas - 如何在熊猫中将多列设置为索引
问题描述
我有以下数据:
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
解决方案
你不需要使用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)
推荐阅读
- javascript - 使用数组和 for 循环获取
- c# - C# Json.Net 使用不同的“key”参数反序列化 Json
- powershell - Power Shell CSV 转换
- angular - Angular 6从解码的字符串base 64中提取值
- reactjs - 使用 jest vs react-scripts 测试
- python - 问题:dropna() 方法返回 NaN 值
- python - 分页后重新显示当前标题
- javascript - preventDefault() 不能在('submit') 函数上工作
- python - 熊猫绘图 - sharex 改变绘图中的 x 值
- python - Django 2.1.3 LDAP 身份验证未对后端进行身份验证