gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:12:55 25 4
gpt4 key购买 nike

描述

我在缺少数据的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com