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


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

python - how to get numpy where for 1st True Only

i have array of data as given below.


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

> 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