I have a dataframe organised like so:
x y e
A 0 0.0 1.0 0.01
1 0.1 0.9 0.03
2 0.2 1.3 0.02
...
B 0 0.0 0.5 0.02
1 0.1 0.6 0.02
2 0.2 0.9 0.04
...
etc.
I would like to select rows of a A/B/etc. that fall between certain values in x.
This, for example, works:
p,q=0,1
indices=df.loc[("A"),"x"].between(p,q)
df.loc[("A"),"y"][indices]
Out:
[1.0,0.9]
However, this takes two lines of code, and uses chain indexing. However, what is to me the obvious way of one-lining this doesn't work:
p,q=0,1
df.loc[("A",df[("A"),"x"].between(p,q)),"y"]
Out:
[1.0,0.9]
How can I avoid chain indexing here?
(Also, if anyone wants to explain how to make the "x" column into the indices and thereby avoid the '0,1,2' indices, feel free!)
[Edited to clarify desired output]
df = df.reset_index(level=1, drop=True).set_index('x', append=True)df.query('@p<=x && x<=@q').loc['A','y']would work for the first one.