Kurt Peek Kurt Peek - 4 months ago 11
Python Question

Select values of one array based on a boolean expression applied to another array

Starting with the following array

array([ nan, nan, nan, 1., nan, nan, 0., nan, nan])


which is generated like so:

import numpy as np
row = np.array([ np.nan, np.nan, np.nan, 1., np.nan, np.nan, 0., np.nan, np.nan])


I'd like to get the indices of the sorted array and then exclude the
nans
. In this case, I'd like to get
[6,3]
.

I've come up with the following way to do this:

vals = np.sort(row)
inds = np.argsort(row)

def select_index_by_value(indices, values):
selected_indices = []
for i in range(len(indices)):
if not np.isnan(values[i]):
selected_indices.append(indices[i])
return selected_indices

selected_inds = select_index_by_value(inds, vals)


Now
selected_inds
is
[6,3]
. However, this seems like quite a few lines of code to achieve something simple. Is there perhaps a shorter way of doing this?

Answer

Another option:

row.argsort()[~np.isnan(np.sort(row))]
# array([6, 3])
Comments