A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/21058254/pandas-boolean-operation-in-a-python-list/21058331 below:

Pandas Boolean Operation in a Python List

a & b & c is equivalent to

import functools
print(functools.reduce(lambda x,y: x & y, [a, b, c]))

which yields

0    False
1    False
2     True
dtype: bool

Unlike my original answer below (suggesting np.logical_and.reduce), I am confident functools.reduce(lambda x,y: x & y, [a, b, c]) will faithfully return the same Series as a & b & c.

(In Python2.7, reduce is a builtin function. functools.reduce is the same function as reduce. In Python3, reduce was removed from the builtins and only functools.reduce remains. So to future-proof your code, use functools.reduce.)

Edit: Using np.logical_and.reduce([logic]) may not work in all situations. Here is a counterexample:

import pandas as pd
import numpy as np
x = pd.Series([True,True,False,False], index=[1,2,3,4]) 
y = pd.Series([True,True,False,False], index=[1,2,3,4]) 
print(x & y)

prints

1     True
2     True
3    False
4    False
dtype: bool

but np.logical_and.reduce([x,y]) raises a ValueError

    print(np.logical_and.reduce([x,y]))
  File "/data1/unutbu/.virtualenvs/dev/local/lib/python2.7/site-packages/pandas-0.13.0_98_gd9b0c1f-py2.7-linux-i686.egg/pandas/core/generic.py", line 665, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4