2013-08-02 47 views
8

我有熊貓系列的元組索引,這樣的:片熊貓系列元素不在索引中

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中使用日期進行分片時發生的情況。有沒有簡單的方法來實現這一點?

回答

8

這工作,如果你有一個多指標,而不是元組的索引:

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,並創造了一個可怕的黑客...

+0

太棒了,謝謝你的幫助! – Javier

+0

(我會upvote你的答案,但沒有足夠的代表) – Javier