Reputation: 5
I have a boolean list a
such as the following
Time Value
2017-09-02 11:00:00 False
2017-09-02 11:30:00 False
2017-09-02 12:00:00 True
2017-09-02 12:30:00 True
2017-09-02 13:00:00 True
2017-09-02 13:30:00 True
2017-09-02 14:00:00 False
2017-09-02 14:30:00 False
2017-09-02 15:00:00 False
2017-09-02 15:30:00 False
Next I would like to check for False values which are preceded by True Values.
result = (a == 0) & (a.shift(-1) == 1)
The issue is that this condition should be dynamic, which means that I might want to check for values which are False and preceded in N positions by a True value, for instance
N = 2
result = (a == 0) & ( (a.shift(-1) == 1) | a.shift(-2) == 1) )
N = 3
result = (a == 0) & ( (a.shift(-1) == 1) | a.shift(-2) == 1) | a.shift(-3) == 1) )
How can I dynamically define this conditional using N as an input parameter in a nice (pythonic?) way?
Upvotes: 0
Views: 371
Reputation: 863341
Use np.logical_or.reduce
and create conditions in list comprehensions:
N = 2
result = (a == 0) & np.logical_or.reduce([a.shift(-x) == 1 for x in range(1, N + 1)])
Upvotes: 1