Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split numpy array into segments where condition is met

I have an array like so:

arr = np.array([1, 2, 3, 4, -5, -6, 3, 5, 1, -2, 5, -1, -1, 10])

I want to get rid of all negative values, and split the array at each index where there was a negative value. The result should look like this:

split_list = [[1, 2, 3, 4], [3, 5, 1], [5], [10]]

I know how to do this using list comprehension, but since the array can get quite large and I have to do the calculation many times, I want to find a solution using numpy. I found this https://www.geeksforgeeks.org/python-split-list-into-lists-by-particular-value/, which I can use to split the array where there are negative values, but I can't simultaneously remove them.

like image 960
Alex V. Avatar asked Sep 08 '26 06:09

Alex V.


1 Answers

Note that instead of numpy, you could make use of itertools.groupby this way (though, judging on this: NumPy grouping using itertools.groupby performance, pure numpy will likely be more efficient):

import numpy as np
from itertools import groupby

arr = np.array([1, 2, 3, 4, -5, -6, 3, 5, 1, -2, 5, -1, -1, 10])
split_list = [list(group) for key, group in groupby(arr, key=lambda x:x>=0) if key]

# [[1, 2, 3, 4], [3, 5, 1], [5], [10]]
like image 198
Swifty Avatar answered Sep 09 '26 19:09

Swifty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!