Slice pandas series with elements not in the index
pandas, python, series, slice
Solution
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...
Problem
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?