我有以下的pandas数据(与这里的示例相关:pandas: slice a MultiIndex by range of secondary index)
如果我在这两个多重索引上切片,它会像这样工作:
但是我怎样才能仅仅在二级索引"time"上切片,例如在time=0时获取每一行的第一个索引?以下方法行不通:
import numpy as np
import pandas as pd
variable = np.repeat(['a','b','c'], [5,5,5])
time = [0,1,5,10,20,0,1,5,10,20,0,1,5,10,20]
arra = [variable, time]
index=pd.MultiIndex.from_arrays(arra, names=("variable", "time"))
s = pd.Series(
np.random.randn(len(sequence)),
index=index
)
输出将会是:
# In [1]: s
variable time
a 0 -1.284692
1 -0.313895
5 -0.980222
10 -1.452306
20 -0.423921
b 0 0.248625
1 0.183721
5 -0.733377
10 1.562653
20 -1.092559
c 0 0.061172
1 0.133960
5 0.765271
10 -0.648834
20 0.147158
dtype: float64
如果我在这两个多重索引上切片,它会像这样工作:
# In [2]: s.loc[("a",0),:]
variable time
a 0 1.583589
1 -1.081401
5 -0.497904
10 0.352880
20 -0.179062
dtype: float64
但是我怎样才能仅仅在二级索引"time"上切片,例如在time=0时获取每一行的第一个索引?以下方法行不通:
# In [3]: s.loc[(0),:]
KeyError: 0
我应该在这里怎么做?