0

How can I select all values where the 'displacement' (second level of MultiIndex) is above a certain value, say > 2?

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]

I tried reading the docs but couldn't work it out, even trying IndexSlice.

Bonus points: how to I select a range, say between 2 and 4?

Thanks in advance for any help.

blokeley
  • 6,726
  • 9
  • 53
  • 75

1 Answers1

0
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)]

Inspired by https://stackoverflow.com/a/18103894/268075

Community
  • 1
  • 1
blokeley
  • 6,726
  • 9
  • 53
  • 75