在熊猫数据框中添加布尔列

时间:2021-04-20 11:34:42

标签: python pandas

使用此代码,我想创建布尔列 check 以检查列 LTP 中的值是否在列 val 的 0.10% 范围内。

所有值都是 float 类型。

   df = df.assign(upper_range=lambda x: (x['val'] +(x['val'] * 0.001)))
   df = df.assign(lower_range=lambda x: ( x['val']- (x['val'] * 0.001) ) )
   df = df.assign(check=lambda x: (x['LTP'] >= x['lower_range'] & x['LTP'] <= x['upper_range']))

此代码出错

    TypeError: ufunc 'bitwise_and' not supported for the input types, 
    and the inputs could not be safely coerced to any supported types according to the casting rule 
    ''safe''

    TypeError: unsupported operand type(s) for &: 'float' and 'float'

为了比较,我也尝试使用 and 而不是 & 发生以下错误

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

没有正确关闭 (),每个条件都需要括号:

 df = df.assign(check=lambda x: (x['LTP'] >= x['lower_range']) & (x['LTP'] <= x['upper_range']))