I am trying to implement a function that identifies the first consecutive occurrences in a Pandas Series
, which has already been masked with the condition I wanted: (e.g.)
[True, True, True, False, True, False, True, True, True, True]
I want the above input to give the result of 3
, i.e., there are 3 True
occurrences in a row from the beginning of the series.
I am aware that a big for
loop would do the work, but are there any vectorized / Pandas-centric way to go around it?
Thank you very much.
I initally hadn't got that the question was about pandas Series. The answer below uses list methods, but is still valid if the pandas Series are converted to list (method a.to_list()
).
Without any import, you can find the first occurrence of False
by using the method index
of list, and this will be the number you are looking for:
a = [True, True, True, False, True, False, True, True, True, True]
n_head_true = a.index(False) if False in a else len(a)
print(n_head_true)
> 3
a = [True, True, True]
n_head_true = a.index(False) if False in a else len(a)
print(n_head_true)
> 3
a = [False, True, True]
n_head_true = a.index(False) if False in a else len(a)
print(n_head_true)
> 0
The if
is needed because index
gives error if all values are True.
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