Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫多索引切片”;“级别类型不匹配”;_Python_Pandas_Slice_Multi Index - Fatal编程技术网

Python 熊猫多索引切片”;“级别类型不匹配”;

Python 熊猫多索引切片”;“级别类型不匹配”;,python,pandas,slice,multi-index,Python,Pandas,Slice,Multi Index,我从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_i

我从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
它在0.13.1中运行良好,并且似乎特别适用于带日期的多索引。
我在这里做错了什么吗?

发生此错误是因为您试图对索引中未包含的日期(标签)进行切片。要解决此级别不匹配错误并在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'
get\u level\u values()
和比较运算符为索引器设置真/假索引值掩码

无论字符串是否在索引中,使用字符串或日期对象进行切片通常在使用单个索引的熊猫中工作,但不适用于多索引数据帧。虽然您尝试使用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)设置索引的一种正确方法是使用datetime对象的任一字符串将索引设置为日期范围,如:

df.set_index("date").loc[pd.date_range('2013-12-30', '2014-12-03')]