为什么pandas布尔掩码不能给予我想要的结果?我在这里遗漏了什么?

xzv2uavs  于 2023-11-15  发布在  其他
关注(0)|答案(1)|浏览(126)

所有的帮助赞赏以下:
我实现了以下代码,它通过4个步骤过滤pandas dataFrame的结果:

mask =  ( (stock_hist['confirmed']== True) &\
    (stock_hist['prevday_confirmed'] == False) & \
     (stock_hist['nextday_confirmed'] == False) &\
         (stock_hist['nextday_above_supp'] == True) &\
             (stock_hist['prevday_above_supp'] == True)
         ) 
result1 = stock_hist[mask]    

mask = ( \
    (stock_hist['confirmed'] == True) & \
        (stock_hist['prevday_confirmed'] == False) & \
            (stock_hist['prevday_above_supp'] == True) &\
    (stock_hist['nextday_confirmed'] == True) & \
        (stock_hist['current_dist'] < stock_hist['nextday_dist']) \
            )          
result2 = stock_hist[mask]    

mask =  ( (stock_hist['confirmed']== True) &\
    (stock_hist['prevday_confirmed'] == True) & \
     (stock_hist['nextday_confirmed'] == False) &\
         (stock_hist['nextday_above_supp'] == True) &\
             (stock_hist['current_dist'] < stock_hist['prevday_dist'])
         ) 
result3 = stock_hist[mask]

mask =  ( (stock_hist['confirmed']== True) &\
    (stock_hist['prevday_confirmed'] == True) & \
     (stock_hist['nextday_confirmed'] == True) &\
         (stock_hist['current_dist'] < stock_hist['prevday_dist']) &\
             (stock_hist['current_dist'] < stock_hist['nextday_dist'])
         ) 
result4 = stock_hist[mask]

result = result1.append([result2, result3, result4])

字符串
现在,这段代码做的正是我期望它做的。
然而,我希望我应该能够在一个单独的面具中做到这一点,就像这样:

mask =  ( (stock_hist['confirmed']== True) &\
        ~(stock_hist['prevday_confirmed'] == False) & \
         ~(stock_hist['nextday_confirmed'] == False) &\
             ~(stock_hist['nextday_above_supp'] == True) &\
                 ~(stock_hist['prevday_above_supp'] == True) \
                     | \
        (stock_hist['confirmed'] == True) & \
            ~(stock_hist['prevday_confirmed'] == False) & \
                ~(stock_hist['prevday_above_supp'] == True) &\
        ~(stock_hist['nextday_confirmed'] == True) & \
            ~(stock_hist['current_dist'] < stock_hist['nextday_dist']) \
                | \
                    
                    :
                    :
                    :


但当我这么做的时候,|作为&?,因为它为整个掩码呈现了一个&?,也为那些被第一个代码成功过滤掉的行呈现了&?。
我错过了什么?

4sup72z8

4sup72z81#

这是一个典型的例子,说明了为什么操作顺序很重要:就像2 + 3 x 4不等于(2 + 3) x 4一样,你需要在你的条件之间再添加一层括号。

(A & B | C & D) != ((A & B) | (C & D))

字符串
在您的情况下,如果掩码必须放在括号之间,以便将它们累积到一个条件中,|

相关问题