cle*_*ent 5 python slice multi-index pandas
我从 0.13.1 转到了 pandas 0.17 版,并且在切片时遇到了一些新错误。
>>> df
date int data
0 2014-01-01 0 0
1 2014-01-02 1 -1
2 2014-01-03 2 -2
3 2014-01-04 3 -3
4 2014-01-05 4 -4
5 2014-01-06 5 -5
>>> df.set_index("date").ix[datetime.date(2013,12,30):datetime.date(2014,1,3)]
int data
date
2014-01-01 0 0
2014-01-02 1 -1
2014-01-03 2 -2
>>> df.set_index(["date","int"]).ix[datetime.date(2013,12,30):datetime.date(2014,1,3)]
Traceback (most recent call last):
...
TypeError: Level type mismatch: 2013-12-30
Run Code Online (Sandbox Code Playgroud)
它在 0.13.1 上运行良好,而且似乎特定于带日期的多索引。我在这里做错了吗?
小智 3
出现此错误的原因是您尝试对索引中未包含的日期(标签)进行切片。要解决此级别不匹配错误并返回可能位于或不位于 df 多索引范围内的值,请使用:
df.loc[df.index.get_level_values(level = 'date') >= datetime.date(2013,12,30)]
# You can use a string also i.e. '2013-12-30'
Run Code Online (Sandbox Code Playgroud)
get_level_values()比较运算符为索引器设置 True/False 索引值的掩码。
使用字符串或日期对象进行切片通常适用于具有单个索引的 Pandas,无论字符串是否在索引中,但不适用于多索引数据帧。尽管您尝试使用 datetime.date(2013,12,30) : datetime.date(2014,1,3) set_index 调用将索引设置为从 2013-12-30 到 2014-01-03,但生成的 df 索引为从 2014-01-01 到 2014-01-03。为包括 2013-12-30 在内的日期设置索引的一种正确方法是使用日期时间对象的任一字符串将索引设置为日期范围,例如:
df.set_index("date").loc[pd.date_range('2013-12-30', '2014-12-03')]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4227 次 |
| 最近记录: |