提问人:thenatlog 提问时间:10/6/2022 最后编辑:thenatlog 更新时间:10/6/2022 访问量:68
pandas - 条件之后的索引数据
pandas - index data that comes after conditional
问:
我有以下时间序列
[0,1,2,3,2,1,0,1,2,3,2,1,0]
我想对所有值进行布尔索引:
- 包括 & 在 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
答:
1赞
dermen
10/6/2022
#1
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])
评论
0赞
thenatlog
10/6/2022
这非常接近,第 7 个索引处的 [1] 被计为 True,而它应该是 False
0赞
dermen
10/6/2022
哦,我明白了,我太仓促了。新的解决方案不那么漂亮。并且可能没有得到所有的边缘情况(例如,如果没有 2)..但它似乎符合您想要的结果
评论