Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split numpy array at multiple values?

Based on my question Fastest way to approximately compare values in large numpy arrays? I was looking for ways to split an array as I wanted. I have a sorted array (2D, sorted by values in one column), and want to split it into multiple arrays. Not of equal length based on index, but of equal range in values. The closest question I found is Split array at value in numpy but I'd like to do something a bit different. Say I have (1D example):

[0.1, 3.5, 6.5, 7.9, 11.4, 12.0, 22.3, 24.5, 26.7, 29.9]

and I want to split it into ranges [0,10) [10,20) [20,30] so it becomes

[0.1, 3.5, 6.5, 7.9] [11.4, 12.0] [22.3, 24.5, 26.7, 29.9]
like image 210
Tristan Klassen Avatar asked Aug 01 '12 20:08

Tristan Klassen


People also ask

How do you split an array into multiple arrays in Python?

Splitting NumPy Arrays Splitting is reverse operation of Joining. Joining merges multiple arrays into one and Splitting breaks one array into multiple. We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.

How do you split an array into two parts in Python?

Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation : Split from index 1 and first part add to the end.

How do I divide an array in NumPy?

divide() in Python. numpy. divide(arr1, arr2, out = None, where = True, casting = 'same_kind', order = 'K', dtype = None) : Array element from first array is divided by elements from second element (all happens element-wise).

How do you divide an array into two parts?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.


1 Answers

The 1d case can be done like this

>>> A = np.array([0.1, 3.5, 6.5, 7.9, 11.4, 12.0, 22.3, 24.5, 26.7, 29.9])
>>> split_at = A.searchsorted([10, 20])
>>> B = numpy.split(A, split_at)

This also works in 2d, if I understood your question correctly, for example:

>>> A = array([[  0.1,   0. ],
               [  3.5,   1. ],
               [  6.5,   2. ],
               [  7.9,   3. ],
               [ 11.4,   4. ],
               [ 12. ,   5. ],
               [ 22.3,   6. ],
               [ 24.5,   7. ],
               [ 26.7,   8. ],
               [ 29.9,   9. ]])
>>> split_at = A[:, 0].searchsorted([10, 20])
>>> B = numpy.split(A, split_at)
>>> B
[array([[ 0.1,  0. ],
       [ 3.5,  1. ],
       [ 6.5,  2. ],
       [ 7.9,  3. ]]),
 array([[ 11.4,   4. ],
       [ 12. ,   5. ]]),
 array([[ 22.3,   6. ],
       [ 24.5,   7. ],
       [ 26.7,   8. ],
       [ 29.9,   9. ]])]
like image 64
Bi Rico Avatar answered Sep 20 '22 03:09

Bi Rico