0

Is there a straightforward way to generate two numpy arrays from one based on one logical test?

import numpy as np
x = np.array([1,2,3,4,5,6,7,8])
y = x[x%2==0]
z = x[x%2==1]

I don't want to perform the second test for z. Obviously z is simply x with elements from y removed. Can I simply extract z from x with the help of y? Thanks for your help.

  • I would suggest to go through this [link](https://stackoverflow.com/questions/40055835/removing-elements-from-an-array-that-are-in-another-array) – Sai Sreenivas Jul 13 '20 at 16:36
  • `cond = (x%2 == 0)` `y = x[cond]` `z = x[np.logical_not(cond)]` – alani Jul 13 '20 at 16:53

2 Answers2

0

Try this:

import numpy as np
x = np.array([1,2,3,4,5,6,7,8])
y = x[x%2==0]
z = y-1
0

With the new dtype aware sort functions it is actually pretty fast to argsort and split the condition array:

def pp():        
    order = cond.argsort(kind="stable")
    if cond[order[0]]:                          
        return a[:0],a                          
    elif not cond[order[-1]]:
        return a,a[:0]
    split = cond.searchsorted(True,sorter=order)
    return a[order[:split]],a[order[split:]]

def OP():
    return a[~cond],a[cond]


a = np.arange(1000)
cond = a%2 == 0

timeit(OP,number=1000)
# 0.012416471960023046
timeit(pp,number=1000)
# 0.009316607960499823
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99