0

I tried to extract a value range from a pandas column using loc but I fail with:

df.loc[0.5<df['a']<1.5, ['a']]

What is the correct pandas way to do this?

4

1 回答 1

2

Use Series.between:

df.loc[df['a'].between(0.5, 1.5, inclusive=False), ['a']]

Or chain conditions with & for bitwise AND:

df.loc[(df['a'] > 0.5) & (df['a'] < 1.5), ['a']]

Or DataFrame.query with select a to one column DataFrame:

df[['a']].query("0.5 < a < 1.5")
#alternative
#df.query("0.5 < a < 1.5")[['a']]
于 2020-01-31T07:53:22.140 回答