[英]how to get numpy where for 1st True Only
我有如下給出的數據數組。
a=np.array([1,2,3,4,5,6,7,8,1,2,3,4,5,6])
我想獲得像a>5
這樣的條件格式
我可以用np.where
得到它。 但是 np.where 是連續檢查下一個真
np.where(a>5,'T','F')
> array(['F', 'F', 'F', 'F', 'F', 'T', 'T', 'T', 'F', 'F', 'F', 'F', 'F', 'T'], dtype='<U1')
我想跳過連續的真值,比如當a>5
到 6 時,它的True
值,但對於 7,它也是我不想要的True
值。 我只想要第一個。
但是,如果值從 7 下降到 4 並再次上升到 6,那么 6 應該是True
您可以使用np.roll
移動值,然后檢查原始元素是否為 True 並且移動的元素是否為 False
a_bool = a > 5
a_shifted_bool = np.roll(a_bool, 1)
a_shifted_bool[0] = False # first element is last element of a_bool, which we need to ignore
np.where(a_bool & ~a_shifted_bool, 'T', 'F')
array(['F', 'F', 'F', 'F', 'F', 'T', 'F', 'F', 'F', 'F', 'F', 'F', 'F',
'T'], dtype='<U1')
我猜@Suraj S 用最佳時間分析股票來買賣股票。
我嘗試了其他示例,我認為@ggaurav 回答是一個好方法,我在您的回答中學到了更多。
import numpy as np
a=np.array([1,2,3,4,5,6,7,8,1,2,3,4,5,6,4,5,6,7,8,4,2,3,6,4,7,9,4,1,2,3,2,5])
a_bool = a > 5
a_shifted_bool = np.roll(a_bool, 1)
a_shifted_bool[0] = False # first element is last element of a_bool, which we need to ignore
np.where(a_bool & ~a_shifted_bool, 'T', 'F')
array(['F', 'F', 'F', 'F', 'F', 'T', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'T', 'F', 'F', 'T', 'F', 'F', 'F', 'F', 'F', 'T', 'F', 'T', 'F', 'F', 'F', 'F', 'F', 'F', 'F'], dtype='<U1')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.