问题描述
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数据框列中选择一个值范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!