Home > Back-end >  Count number of transitions in each row of a Numpy array
Count number of transitions in each row of a Numpy array

Time:10-27

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.

CodePudding user response:

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])
  • Related