[英]Slice pandas series with elements not in the index
我有一個由元組索引的熊貓系列,如下所示:
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中使用日期切片時發生的情況。 有沒有一種簡單的方法來實現這一目標?
如果您有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
在之前的編輯中,我曾建議這可能是一個錯誤 ,並創造了一個可怕的黑客......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.