在python/numpy中执行以下操作的最简单的方法是什么?
x开始x < .5x的返回索引发布于 2015-09-30 18:32:49
一种解决办法是:
x创建掩码示例:
import numpy as np
# x = np.random.rand(4)
x = np.array([0.96924269, 0.30592608, 0.03338015, 0.64815553])
solution = np.array([2, 1])
sorted_idx = np.argsort(x)
idx_mask = (x[sorted_idx] < 0.5)
sorted_filtered_idx = sorted_idx[idx_mask]
assert np.all(sorted_filtered_idx == solution)发布于 2015-09-30 19:02:04
在这里,找到x < 0.5和x.argsort()的面具似乎是强制性的。有了这两个之后,就可以使用排序索引对掩码数组进行排序,并在排序索引上使用这个掩码返回与满足掩蔽条件的排序索引对应的索引。因此,您需要再添加一行代码,就像-
mask = x < 0.5
sort_idx = x.argsort()
out = sort_idx[mask[sort_idx]]一步一步的跑-
In [56]: x
Out[56]: array([ 0.8974009 , 0.30127187, 0.71187137, 0.04041124])
In [57]: mask
Out[57]: array([False, True, False, True], dtype=bool)
In [58]: sort_idx
Out[58]: array([3, 1, 2, 0])
In [59]: mask[sort_idx]
Out[59]: array([ True, True, False, False], dtype=bool)
In [60]: sort_idx[mask[sort_idx]]
Out[60]: array([3, 1])发布于 2015-09-30 19:17:22
屏蔽阵列简洁(但可能不是特别有效)
x = np.random.rand(4);
inverse_mask = x < 0.5
m_x = np.ma.array(x, mask=np.logical_not(inverse_mask))
sorted_indeces = m_x.argsort(fill_value=1)
filtered_sorted_indeces = sorted_indeces[:np.sum(inverse_mask)]https://stackoverflow.com/questions/32873263
复制相似问题