python - 具有缺失数据的 boolean 系列的 pandas.eval

标签 python pandas boolean eval missing-data

描述

我在缺少数据的 boolean 系列上使用 pandas.eval

为此,我使用索引器标记非空值,并使用 .loc 仅将 .eval 应用于具有非缺失数据的行。

使用表达式 ~boolnot(bool) 应用逻辑非运算符返回 -1 或 -2。

我知道这是因为我的 boolean 系列由于缺少值而被转换为对象类型,但我想知道:

  • 为什么输出 -1 和 -2?
  • 在缺少数据的 boolean 系列上使用 .eval 的正确方法是什么?

例子

这是一个使用 pandas 0.20.3 的可重现示例。

df = pd.DataFrame({'bool': [True, False, None]})
    bool
0   True
1  False
2   None

indexer = ~pd.isnull(df['bool'])
0     True
1     True
2    False
Name: bool, dtype: bool

df.loc[indexer].eval('~bool')
0    -2
1    -1
Name: bool, dtype: object

最佳答案

对于eval~ 映射到op.invert 作为seen in the source code here .

_unary_ops_syms = '+', '-', '~', 'not'
_unary_ops_funcs = op.pos, op.neg, op.invert, op.invert
_unary_ops_dict = dict(zip(_unary_ops_syms, _unary_ops_funcs))

因此,当您的 Series 是旧的 object 类型时,您在这里看到的是

>>> ~True
-2
>>> ~False
-1

# or with your Series
>>> ~pd.Series(True, dtype='object')
0    -2
dtype: object

你想要的地方

>>> ~pd.Series(True)
0    False
dtype: bool

输出 ~True -> -2~False -> -1 是因为 boolint 的子类 在Python中,-2、-1分别是1和0的按位补码。


明显的解决方案是在额外的 setp 中预先使用 astype(bool) 将 Series 转换为 bool 类型,或者如果由于某种原因您之前无法这样做eval,

>>> df.loc[indexer].eval('~bool.astype("bool")')
0    False
1     True
Name: bool, dtype: bool

关于python - 具有缺失数据的 boolean 系列的 pandas.eval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47305110/

相关文章:

python - 从列中过滤掉非数字值

python - 正则表达式拆分包装模式

linux - 在 Linux 文件权限上使用 boolean AND

c++ - 为什么 -ffast-math 选项会破坏我的 bool 条件

python - 命名空间包和 pip install -e

python - xlsxwriter可以使用另一个文件作为模板吗?

python - 如何用多列替换 Pandas 数据框中的单元格?

python - 创建循环以从数据框中动态选择行,然后将所选行附加到另一个数据框 : df. query()

python - 从 pandas Dataframe 列制作条形图

xcode - 如何从 Swift 中的函数返回 boolean 值