python - 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?
解决方案
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']]
推荐阅读
- python - 删除行时如何检查多个数据
- python-3.x - 如何使用 distutils 将 C 扩展构建为 C 扩展主模块的子模块?
- r - 将引用的参数传递给容器的 azure webapp --startup-file
- mobile - 您可以在 Edge 移动应用程序中使用 devtools 吗?
- laravel - 在 laravel 中保存多个外键
- mongodb - 如何从docker连接到mongodb?
- kframework - 解决K框架教程中练习的难点
- c# - 在c#中比较两个不同CSV文件的行值
- javascript - 无法将按钮单击分配给锚标记角度中的按钮
- excel - 使用 ADODB 从 Excel VBA 到 Oracle DB 的连接不再有效