首页 > 解决方案 > 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?

标签: pythonpandasslicepandas-loc

解决方案


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

推荐阅读