问题描述
import pandas as pd
import numpy as np
data = 'filename.csv'
df = pd.DataFrame(data)
df
one two three four five
a 0.469112 -0.282863 -1.509059 bar True
b 0.932424 1.224234 7.823421 bar False
c -1.135632 1.212112 -0.173215 bar False
d 0.232424 2.342112 0.982342 unbar True
e 0.119209 -1.044236 -0.861849 bar True
f -2.104569 -0.494929 1.071804 bar False
我想为某一列选择一个范围,比如列 two
.我想选择 -0.5 和 +0.5 之间的所有值.如何做到这一点?
I would like to select a range for a certain column, let's say column two
. I would like to select all values between -0.5 and +0.5. How does one do this?
我希望使用
-0.5 < df["two"] < 0.5
但这(自然)给出了一个ValueError:
But this (naturally) gives a ValueError:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我试过了
-0.5 (< df["two"] < 0.5)
但这会输出所有 True
.
正确的输出应该是
0 True
1 False
2 False
3 False
4 False
5 True
在 pandas 数据框列中查找一系列值的正确方法是什么?
What is the correct way to find a range of values in a pandas dataframe column?
问题
使用 .between()
和
df['two'].between(-0.5, 0.5, inclusive=False)
会有区别
-0.5 < df['two'] < 0.5
和像
-0.5 =< df['two'] < 0.5
?
推荐答案
使用 between
与 inclusive=False
表示严格不等式:
Use between
with inclusive=False
for strict inequalities:
df['two'].between(-0.5, 0.5, inclusive=False)
inclusive
参数决定是否包含端点(True
: <=
, False
: <
).这适用于两个标志.如果您想要混合不等式,则需要明确编码:
The inclusive
parameter determines if the endpoints are included or not (True
: <=
, False
: <
). This applies to both signs. If you want mixed inequalities, you'll need to code them explicitly:
(df['two'] >= -0.5) & (df['two'] < 0.5)
这篇关于如何在 pandas 数据框列中选择一系列值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!