2

在代码中:

df = pd.DataFrame([[False, 0], [False, 1], [False, 2], [False, 2], [False, 3], [False, 4], [False, 5]], 
        columns=['cond1', 'cond2'])
df['test'] = (~df['cond1']) & (df['cond2'])

我期望在test列中获得True除第一行之外的所有行中的值,因为除 0 之外的任何数字的真实值都是True. 但是,我得到False的值cond2是 2 或 4。为什么?

上述代码的输出:

   cond1 cond2 test

0  False 0     False 

1  False 1     True 

2  False 2     False 

3  False 2     False 

4  False 3     True 

5  False 4     False 

6  False 5     True 
4

1 回答 1

1

当您对 pandas 列进行“&”操作时,python 无法解释其他数字。它正在执行设置操作而不是布尔操作。因此,您需要通过将第二列转换为 bool 来帮助它:

df = pd.DataFrame([[False, 0], [False, 1], [False, 2], [False, 2], [False, 3], [False, 4], [False, 5]], 
        
columns=['cond1', 'cond2'])

df['test'] = (~df['cond1']) & ((df['cond2'].astype(bool)))
于 2021-05-20T13:55:16.803 回答