我试图修改DataFrame df 只包含 closing_price 列中的值介于99和101之间的行,并尝试使用下面的代码执行此操作 .
df
closing_price
但是,我得到了错误
ValueError:系列的真值是不明确的 . 使用a.empty,a.bool(),a.item(),a.any()或a.all()
我想知道是否有办法在不使用循环的情况下执行此操作 .
df = df[(99 <= df['closing_price'] <= 101)]
您应该使用 () 对布尔向量进行分组以消除歧义 .
()
df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]
还要考虑series between:
df = df[df['closing_price'].between(99, 101, inclusive=True)]
有一个更好的选择 - 使用query()方法:
In [58]: df = pd.DataFrame({'closing_price': np.random.randint(95, 105, 10)}) In [59]: df Out[59]: closing_price 0 104 1 99 2 98 3 95 4 103 5 101 6 101 7 99 8 95 9 96 In [60]: df.query('99 <= closing_price <= 101') Out[60]: closing_price 1 99 5 101 6 101 7 99
UPDATE: 回答评论:
我喜欢这里的语法,但在尝试与expresison结合时倒下了; df.query('(mean 2 * sd)<= closing_price <=(mean 2 * sd)')
In [161]: qry = "(closing_price.mean() - 2*closing_price.std())" +\ ...: " <= closing_price <= " + \ ...: "(closing_price.mean() + 2*closing_price.std())" ...: In [162]: df.query(qry) Out[162]: closing_price 0 97 1 101 2 97 3 95 4 100 5 99 6 100 7 101 8 99 9 95
newdf = df.query('closing_price.mean() <= closing_price <= closing_price.std()')
要么
mean = closing_price.mean() std = closing_price.std() newdf = df.query('@mean <= closing_price <= @std')
而不是这个
你应该用它
df = df[(df['closing_price']>=99 ) & (df['closing_price']<=101)]
我们必须使用NumPy的按位逻辑运算符|,&,〜,^来进行复合查询 . 此外,括号对于运算符优先级很重要 .
欲了解更多信息,请访问以下链接:Comparisons, Masks, and Boolean Logic
5 回答
您应该使用
()
对布尔向量进行分组以消除歧义 .还要考虑series between:
有一个更好的选择 - 使用query()方法:
UPDATE: 回答评论:
要么
而不是这个
你应该用它
我们必须使用NumPy的按位逻辑运算符|,&,〜,^来进行复合查询 . 此外,括号对于运算符优先级很重要 .
欲了解更多信息,请访问以下链接:Comparisons, Masks, and Boolean Logic