我有以下时间序列
[0,1,2,3,2,1,0,1,2,3,2,1,0]
我想对以下所有值进行布尔索引:
- include&在2之后
- 大于0
- 终止于0
如果满足条件,则应产生以下矢量
[False,False,True,True,True,True,False,False,True,True,True,True,False]
我曾试图用逻辑查询的组合来解决它,但没有用
frame['boolean'] = False
frame['boolean'].loc[(frame['sequence'].gt(2)) & (frame['boolean'].shift(1).eq(False)] = True
Id为此使用numpy(它与pandas系列配合良好(
import numpy as np
a = np.array([0,1,2,3,2,1,0,1,2,3,2,1,0])
result = a > 0
where_zero = np.where(a==0)[0]
where_two = list(np.where(a==2)[0])
# note if where_two is an empty list, then the result should simply be all False, right ?
for x1 in where_zero:
while 1:
try:
x2 = where_two.pop(0)
except IndexError:
break
if x2 > x1:
break
result[x1:x2] = False
# result
#array([False, False, True, True, True, True, False, False, True,
# True, True, True, False])