Count number of transitions in each row of a Numpy array

Question:

I have a 2D boolean array

a=np.array([[True, False, True, False, True],[True , True, True , True, True], [True , True ,False, False ,False], [False, True , True, False, False], [True , True ,False, True, False]])

I would like to create a new array, providing count of True-False transitions in each row of this array.

The desired result is count=[2, 0, 1, 1, 2]

I operate with a large numpy array, so I don’t apply cycle to browse through all lines.

I tried to adopt available solutions to a 2D array with counting for each line separately, but did not succeed.

Asked By: Anton

||

Answers:

Here is a possible solution:

b = a.astype(int)
c = (b[:, :-1] - b[:, 1:])
count = (c == 1).sum(axis=1)

Result:

>>> count
array([2, 0, 1, 1, 2])
Answered By: Riccardo Bucco
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.