Search code examples
pythonarraysreduction

Python 2d array boolean reduction


I've got a 2D array comprised of boolean values (True,False). I'd like to consolidate the array to a 1D based on a logical function of the contents.

e.g. Input:

[[True, True, False],
 [False, False, False],
 [True, True, True]]

Output (logical AND):

[False,
 False,
 True]

How would this be done without a loop ?


Solution

  • I'm assuming you want to apply logical ANDs to the rows. You can apply numpy.all.

    >>> import numpy as np
    >>> a = np.array([[True, True, False], [False, False, False], [True, True, True]])
    >>> a
    array([[ True,  True, False],
           [False, False, False],
           [ True,  True,  True]])
    >>> 
    >>> np.all(a, axis=1)
    array([False, False,  True])
    

    For a solution without numpy, you can use operator.and_ and functools.reduce.

    >>> from operator import and_
    >>> from functools import reduce
    >>> 
    >>> lst = [[True, True, False], [False, False, False], [True, True, True]]
    >>> [reduce(and_, sub) for sub in lst]
    [False, False, True]
    

    edit: actually, reduce is a bit redundant in this particular case.

    >>> [all(sub) for sub in lst]
    [False, False, True]
    

    does the job just as well.