关于python:从给定级别的MultiIndex系列中选择

Select from given level of MultiIndex Series

如何选择"位移"(MultiIndex的第二级)高于某个值的所有值,例如> 2?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

dicts = {}

index = np.linspace(1, 50)
index[2] = 2.0  # Create a duplicate for later testing

for n in range(5):
    dicts['test' + str(n)] = pd.Series(np.linspace(0, 20) ** (n / 5),
                                       index=index)

s = pd.concat(dicts, names=('test', 'displacement'))

#  Something like this?
s[s.index['displacement'] > 2]

我尝试阅读文档但无法解决,甚至尝试使用IndexSlice。

加分点:如何选择一个范围,比如介于2和4之间?

在此先感谢您的帮助。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pandas as pd
import numpy as np

dicts = {}

index = np.linspace(1, 50)

for n in range(5):
    dicts['test' + str(n)] = pd.Series(np.linspace(0, 20) ** (n / 5),
                                       index=index)

s = pd.concat(dicts, names=('test', 'displacement'))

displacement = s.index.get_level_values('displacement')
r = s.loc[(displacement > 2) & (displacement < 5)]

灵感来自https://stackoverflow.com/a/18103894/268075