Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

python - 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

i can get it with np.where. But np.where is continuous checking for next true

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. 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use np.roll to shift the values and then check if original element is True and shifted element is 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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...