Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an array according to a condition in numpy?

Tags:

python

numpy

For example, I have a ndarray that is:

a = np.array([1, 3, 5, 7, 2, 4, 6, 8])

Now I want to split a into two parts, one is all numbers <5 and the other is all >=5:

[array([1,3,2,4]), array([5,7,6,8])]

Certainly I can traverse a and create two new array. But I want to know does numpy provide some better ways?

Similarly, for multidimensional array, e.g.

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9],
       [2, 4, 7]])

I want to split it according to the first column <3 and >=3, which result is:

[array([[1, 2, 3],
        [2, 4, 7]]), 
 array([[4, 5, 6],
        [7, 8, 9]])]

Are there any better ways instead of traverse it? Thanks.

like image 697
Clippit Avatar asked Oct 05 '11 13:10

Clippit


People also ask

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 split an array into parts in Python?

Using a for loop and range() method, iterate from 0 to the length of the list with the size of chunk as the step. Return the chunks using yield . list_a[i:i+chunk_size] gives each chunk. For example, when i = 0 , the items included in the chunk are i to i + chunk_size which is 0 to (0 + 2)th index.

How do I split a NumPy array vertically?

NumPy: vsplit() function The vsplit() function is used to split an array into multiple sub-arrays vertically (row-wise). Note: vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension.


1 Answers

import numpy as np

def split(arr, cond):
  return [arr[cond], arr[~cond]]

a = np.array([1,3,5,7,2,4,6,8])
print split(a, a<5)

a = np.array([[1,2,3],[4,5,6],[7,8,9],[2,4,7]])
print split(a, a[:,0]<3)

This produces the following output:

[array([1, 3, 2, 4]), array([5, 7, 6, 8])]

[array([[1, 2, 3],
       [2, 4, 7]]), array([[4, 5, 6],
       [7, 8, 9]])]
like image 158
NPE Avatar answered Oct 21 '22 15:10

NPE