Search code examples
pythonpandasslicepandas-loc

Slicing a range from a pandas dataframe column using loc


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?


Solution

  • 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']]