Javier
Javier

Reputation: 742

Slice pandas series with elements not in the index

I have a pandas series indexed by tuples, like this:

from pandas import Series
s = Series({(0, 0): 1, (0, 1): 2, (0, 3): 3, (1, 0): 1, (1, 2): 4, (3, 0): 5})

I want to slice such a series by using indexes that are also tuples (using lexicographic ordering), but not necessarily in the index. Slicing seems to work when I pass an index that is on the series:

s[:(1,0)]
(0, 0)    1
(0, 1)    2
(0, 3)    3
(1, 0)    1
dtype: int64

but if I try slicing by an index which is not on the series there is an error:

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

Ideally I'd like to get the series elements indexed by (0, 0), (0, 1), (0, 3), (1, 0), similar to what happens when slicing using dates in TimeSeries. Is there a simple way to achieve this?

Upvotes: 8

Views: 2357

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375575

This works if you have a MultiIndex rather than an index of tuples:

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

In a previous edit I had suggested this could be a bug, and had created an awful hack...

Upvotes: 8

Related Questions