Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain the element-wise logical NOT of a pandas Series?

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 

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

like image 319
Louis Thibault Avatar asked Apr 14 '13 10:04

Louis Thibault


People also ask

How do you get element from pandas Series?

In order to access the series element refers to the index number. Use the index operator [ ] to access an element in a series. The index must be an integer. In order to access multiple elements from a series, we use Slice operation.

What is the difference between a Pandas Series and a Pandas DataFrame?

Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data.

What is element wise in pandas?

Element-wise means handling data element by element.


1 Answers

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 

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 

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.

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

like image 113
unutbu Avatar answered Oct 13 '22 23:10

unutbu