切片熊猫系列与元素不在索引中

时间:2013-08-02 10:49:44

标签: 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
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)索引的系列元素,类似于在TimeSeries中使用日期切片时发生的情况。有没有一种简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:8)

如果您有MultiIndex而不是元组索引,则此方法有效:

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

在之前的编辑中,我曾建议这可能是a bug,并且创建了一个非常糟糕的黑客......

相关问题