Herbert
Herbert

Reputation: 5645

Is there a numpy.there?

I was wondering whether there is a opposite of numpy.where (going from booleans to indices) which goes from indices to booleans; for example numpy.there.

A possible implementation could use scipy's sparse matrices:

from scipy.sparse import csr_matrix
numpy_there = lambda there, n: numpy.array(
  csr_matrix((
    [1]*len(there),
    there,
    [0, len(there)]
  ),
  shape=(1,n),
  dtype=numpy.bool
).todense())[0,:]

numpy_there([1,4,6,7,12], 15)

array([False,  True, False, False,  True, False,  True,  True, False, False, False, False,  True, False, False], dtype=bool)

But obviously, this requires scipy and is quite verbose, whereas given numpy.where I would also expect a numpy.there.

Upvotes: 2

Views: 56

Answers (1)

Divakar
Divakar

Reputation: 221714

You can use np.in1d with np.arange to simulate such a behaviour, like so -

def numpy_there(A,val):
    return np.in1d(np.arange(val),A)

Sample run -

In [14]: A
Out[14]: array([ 1,  4,  6,  7, 12])

In [15]: numpy_there(A,15)
Out[15]: 
array([False,  True, False, False,  True, False,  True,  True, False,
       False, False, False,  True, False, False], dtype=bool)

You can use a bit more verbose implementation using initialization with boolean False values and then assigning True values at A indexed positions, like so -

def numpy_there_v2(A,val):
    out = np.zeros(val,dtype=bool)
    out[A] = 1
    return out

Upvotes: 3

Related Questions