Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.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_Series_Slice - Fatal编程技术网

Python 对索引中不包含元素的系列进行切片

Python 对索引中不包含元素的系列进行切片,python,pandas,series,slice,Python,Pandas,Series,Slice,我有一个按元组索引的熊猫系列,如下所示: from pandas import Series s = Series({(0, 0): 1, (0, 1): 2, (0, 3): 3, (1, 0): 1, (1, 2): 4, (3, 0): 5}) 我想通过使用同样是元组的索引(使用字典排序)来分割这样的序列,但不一定在索引中。当我传递序列上的索引时,切片似乎起作用: s[:(1,0)] (0, 0) 1 (0, 1) 2 (0, 3) 3 (1, 0) 1 dtyp

我有一个按元组索引的熊猫系列,如下所示:

from pandas import Series
s = Series({(0, 0): 1, (0, 1): 2, (0, 3): 3, (1, 0): 1, (1, 2): 4, (3, 0): 5})
我想通过使用同样是元组的索引(使用字典排序)来分割这样的序列,但不一定在索引中。当我传递序列上的索引时,切片似乎起作用:

s[:(1,0)]
(0, 0)    1
(0, 1)    2
(0, 3)    3
(1, 0)    1
dtype: int64
但如果我尝试按不在序列上的索引进行切片,则会出现错误:

s[:(1,1)]
...
ValueError: Index(...) must be called with a collection of some kind, 0 was passed

理想情况下,我希望通过(0,0)、(0,1)、(0,3)、(1,0)索引序列元素,类似于在时间序列中使用日期进行切片时发生的情况。有没有一种简单的方法可以实现这一点?

如果您使用的是多索引而不是元组索引,那么这种方法就可以实现:

In [11]: s.index = pd.MultiIndex.from_tuples(s.index)

In [12]: s
Out[12]: 
0  0    1
   1    2
   3    3
1  0    1
   2    4
3  0    5
dtype: int64

In [13]: s[:(1,1)]
Out[13]: 
0  0    1
   1    2
   3    3
1  0    1
dtype: int64
在之前的一次编辑中,我曾建议这可能是,并创造了一个可怕的黑客