如何获得 pandas 系列的按元素逻辑非? [英] How can I obtain the element-wise logical NOT of a pandas Series?

查看:86
本文介绍了如何获得 pandas 系列的按元素逻辑非?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pandas Series object containing boolean values. How can I get a series containing the logical NOT of each value?

例如,考虑一个包含以下内容的系列:

For example, consider a series containing:

True
True
True
False

我想要获得的系列将包含:

The series I'd like to get would contain:

False
False
False
True

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

This seems like it should be reasonably simple, but apparently I've misplaced my mojo =(

推荐答案

要反转布尔系列,请

To invert a boolean Series, 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:

Using 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

自熊猫0.13.0起,系列不再是numpy.ndarray的子类;它们现在是pd.NDFrame的子类.这可能与np.invert(s)不再快于~s-s的原因有关.

As of Pandas 0.13.0, Series are no longer subclasses of numpy.ndarray; they are now subclasses of pd.NDFrame. This might have something to do with why np.invert(s) is no longer as fast as ~s or -s.

注意事项:timeit的结果可能取决于许多因素,包括硬件,编译器,OS,Python,NumPy和Pandas版本.

Caveat: timeit results may vary depending on many factors including hardware, compiler, OS, Python, NumPy and Pandas versions.

这篇关于如何获得 pandas 系列的按元素逻辑非?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆