I have a numpy binary array like this:
Array A = [1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0]
I would like to count how many 0s are there at the left of each 1, and return it in an other array that would look like this for this for this example:
nb_1s = [0, 0, 1, 2, 2, 5]
There are no 0s at the left for the two first 1s so the the first two numbers of the array are 0 etc...
I know that first I have to initiate an array with number of 1s in my array:
def give_zeros(binary_array):
binary_array = np.asarray(binary_array)
nb_zeros = np.zeros(binary_array.sum())
return nb_zeros
But I'm not sure on how to count the number of zeros. Should I iterate in a for loop with 'nditer'? It doesn't seem efficient as i will have to run this function on very large arrays.
Do you have any ideas? Thank you.
You could use:
(A == 0).cumsum()[A > 0]
# array([0, 0, 1, 2, 2, 5])
or:
(~A).cumsum()[A]
# array([0, 0, 1, 2, 2, 5])
if A
is a bool array.
A == 0
is a boolean array which is True
for each 0
:
>>> import numpy as np
>>> A = np.array([1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0])
>>> A == 0
array([False, False, True, False, True, False, False, True, True,
True, False, True, True, True, True], dtype=bool)
You can use cumsum()
to count the number of True
s:
>>> (A == 0).cumsum()
array([0, 0, 1, 1, 2, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9])
You only need the values where A > 0
:
>>> (A == 0).cumsum()[A > 0]
array([0, 0, 1, 2, 2, 5])
Done!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With