首页 文章

如何获得pandas系列的元素逻辑NOT?

提问于
浏览
138

我有一个包含布尔值的pandas Series 对象 . 如何获得包含每个值的逻辑 NOT 的系列?

例如,考虑一个系列包含:

True
True
True
False

我想要的系列将包含:

False
False
False
True

这似乎应该相当简单,但显然我错了我的mojo =(

4 回答

  • 5

    要反转布尔系列,use ~s

    In [7]: s = pd.Series([True, True, False, True])
    
    In [8]: ~s
    Out[8]: 
    0    False
    1    False
    2     True
    3    False
    dtype: bool
    

    使用Python2.7,NumPy 1.8.0,Pandas 0.13.1:

    In [119]: s = pd.Series([True, True, False, True]*10000)
    
    In [10]:  %timeit np.invert(s)
    10000 loops, best of 3: 91.8 µs per loop
    
    In [11]: %timeit ~s
    10000 loops, best of 3: 73.5 µs per loop
    
    In [12]: %timeit (-s)
    10000 loops, best of 3: 73.5 µs per loop
    

    从Pandas 0.13.0开始,Series不再是 numpy.ndarray 的子类;它们现在是 pd.NDFrame 的子类 . 这可能与为什么 np.invert(s) 不再像 ~s-s 一样快 .

    警告: timeit 结果可能因许多因素而异,包括硬件,编译器,操作系统,Python,NumPy和Pandas版本 .

  • 163

    我试试看:

    In [9]: s = Series([True, True, True, False])
    
    In [10]: s
    Out[10]: 
    0     True
    1     True
    2     True
    3    False
    
    In [11]: -s
    Out[11]: 
    0    False
    1    False
    2    False
    3     True
    
  • 10

    @unutbu 's answer is spot on, just wanted to add a warning that your mask needs to be dtype bool, not '对象'. Ie your mask can'曾经有过任何一个南方人 . 请参阅here - 即使您的面具现在是无痣,它仍然是'object'类型 .

    “对象”系列的反转不会引发错误,而是会得到一个不能按预期工作的整数的垃圾掩码 .

    In[1]: df = pd.DataFrame({'A':[True, False, np.nan], 'B':[True, False, True]})
    In[2]: df.dropna(inplace=True)
    In[3]: df['A']
    Out[3]:
    0    True
    1   False
    Name: A, dtype object
    In[4]: ~df['A']
    Out[4]:
    0   -2
    0   -1
    Name: A, dtype object
    

    在与同事谈论这个问题后,我有一个解释:看起来大熊猫正在回归到按位运算符:

    In [1]: ~True
    Out[1]: -2
    
  • 11

    你也可以使用numpy.invert

    In [1]: import numpy as np
    
    In [2]: import pandas as pd
    
    In [3]: s = pd.Series([True, True, False, True])
    
    In [4]: np.invert(s)
    Out[4]: 
    0    False
    1    False
    2     True
    3    False
    

    编辑:性能上的差异出现在Ubuntu 12.04,Python 2.7,NumPy 1.7.0上 - 使用NumPy 1.6.2似乎不存在:

    In [5]: %timeit (-s)
    10000 loops, best of 3: 26.8 us per loop
    
    In [6]: %timeit np.invert(s)
    100000 loops, best of 3: 7.85 us per loop
    
    In [7]: %timeit ~s
    10000 loops, best of 3: 27.3 us per loop
    

相关问题