oscarm
oscarm

Reputation: 2650

Count Booleans by Column in Array of Arrays

I have an array of arrays with booleans:

[[False False  True ..., False  True False]
 [False  True  True ...,  True False  True]
 [False False False ...,  True  True False]
 ..., 
 [False False False ..., False False False]
 [ True  True  True ...,  True  True  True]
 [ True  True  True ...,  True  True  True]]
<type 'numpy.ndarray'>

The following code counts Trues in the rows

results = []
for r in my_array:
   results.append(np.sum(r))

How can I count the number of booleans by column?

Upvotes: 1

Views: 66

Answers (3)

Josh Smeaton
Josh Smeaton

Reputation: 48730

numpy.sum supports summing up an array across multiple axes. Use the 0th axis for columns, and the 1st axis for rows.

>>> arr = np.ndarray(shape=(3, 4), dtype=bool)
>>> arr
array([[False,  True, False,  True],
       [False, False, False,  True],
       [False, False, False, False]], dtype=bool)
>>> np.sum(arr, axis=0)
array([0, 1, 0, 2])
>>> np.sum(arr, axis=1)
array([2, 1, 0])

Upvotes: 3

HelloWorld
HelloWorld

Reputation: 1863

In case you need a pure Python solution I would go with itertools.izip.

# Example
# itertools.izip('ABCD', 'xy') --> Ax By
results = []

for r in itertools.izip(*my_array):
    results.append(sum(r))

Upvotes: 1

BlivetWidget
BlivetWidget

Reputation: 11093

Let's say I have a numpy array

a = numpy.ones([3, 4])
>>> a
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])

numpy has a really neat feature that let's you specify slices in multiple dimensions, such that array[row_indices, col_indices] is meaningful. Consider the following:

>>> sum(a[:,0])
3.0

I just added all row values that have a column index of 0. Replace that value with an iterable and you have your solution.

Upvotes: 0

Related Questions