I have a numpy array:
ar = np.array([True, False, True, True, True])
If the last element is True, I want to remove all of the consecutive true elements at the end of the array. So for example
magic_func(ar) => [True, False]
If ar = [True, False, True, False, True]
. Then
magic_func(ar) => [True, False, True, False]
If ar = [True, False, False]
, the function does nothing, because the last element is False
Is there a one liner in python to do this? using a numpy library or something
Using the groupby function, we can group the together occurring elements as one and can remove all the duplicates in succession and just let one element be in the list. This function can be used to keep the element and delete the successive elements with the use of slicing.
The pop() method will remove the last element from the list, So to remove the last k elements from the Python List, we need to perform the pop() operation k times.
The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
This one line function should work, but looks very nasty and probably not efficient lol. Basically the idea is to find the most right False
and return all values before False
def magic_func(a):
return a[:len(a)-np.where(a[::-1]==False)[0][0]] if np.where(a[::-1]==False)[0].size>0 else a[:0]
>>> a = np.array([False, True, True, True, True])
>>> magic_func(a)
array([False], dtype=bool)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With