[英]how to get numpy where for 1st True Only
i have array of data as given below.我有如下给出的数据数组。
a=np.array([1,2,3,4,5,6,7,8,1,2,3,4,5,6])
i want to get conditional formatting like a>5
我想获得像
a>5
这样的条件格式
i can get it with np.where
.我可以用
np.where
得到它。 But np.where is continuous checking for next true但是 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')
i want to skip the consecutive True Value like when a>5
comes to 6 its True
but for 7 also it is True
which i dont want.我想跳过连续的真值,比如当
a>5
到 6 时,它的True
值,但对于 7,它也是我不想要的True
值。 I want only 1st one.我只想要第一个。
But also if value drops from 7 to 4 and again rise to 6 then that 6 should be True
但是,如果值从 7 下降到 4 并再次上升到 6,那么 6 应该是
True
You can use np.roll
to shift the values and then check if original element is True and shifted element is False您可以使用
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')
I guess @Suraj S analyze stock with Best Times of the value to Buy and Sell Stocks.我猜@Suraj S 用最佳时间分析股票来买卖股票。
I try other example, and I think @ggaurav answer is a good way, I learn more in your answer.我尝试了其他示例,我认为@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.