Search code examples
pythonlist-comprehensionmatrix-indexing

Logical indexing with list comprehensions


My code currently stands as follows:

z = np.diagflat(c).dot(D).dot(x);
idxN, idxP = z<0, z>=0 # logical indexing
y1 = [-1 + np.exp(x)/(1+np.exp(x)) for x in z[idxN]]
y1 = np.array(y1) # Size (504,)
y2 = [-np.exp(-x)/(1+np.exp(-x)) for x in z[idxP]]
y2 = np.array(y2) # Size (496,)

Now I'm trying to form a (1000,) list y which will incorporate y1 or y2 depending on whether the index is +/-.

I'm guessing a list comprehension would be the easiest but I'm struggling with the form. Thanks for your inputs.


Solution

  • Easiest way should be to use the indices to set back the values, then flatten it back, if required:

    z_out = np.empty(z.shape, dtype='float')
    z_out[idxN] = y1                           # values for negative indices
    z_out[idxP] = y2                           # values for positive indices
    
    z_out.flatten()                            # flatten it to 1D array, if required
    

    PS: When you subset a ndarray to create another 1D array, you loose the indices information of the original ndarray. Therefore, for a list comprehension you might need to enumerate over both the newly created 1D arrays and the original ndarray simultaneously.