2015-09-30 41 views
1

在python/numpy中执行以下操作最直接的方法是什么?返回来自经过滤的排序数组,并且有numpy

  • 开始随机阵列x
  • 过滤掉元素x < .5
  • 的大小对应于这些值的(原)x
  • 回报指数的剩余值
+0

是否有任何解决方案适合您? – Divakar

+0

嗨Divakar - 是的......好吧,好像我在所有的时候都处于正确的轨道上 - 烦人地混淆了同时追踪指数和元素:P。感谢您发布解决方案! – ConfusinglyCuriousTheThird

回答

0

我找到那种我解决方法有点麻烦:

import numpy as np 

x = np.random.rand(4); 
filter_bools = x < .5; 
sorted_indices = np.argsort(x) 
sorted_filter = filter_bools[sorted_indices] 

filtered_sorted_indices = sorted_indices[sorted_filter == True] 

print 'x:\t\t\t\t', x 
print 'sorted indices:\t\t\t', sorted_indices 
print 'indices for x < .5, sorted:\t', filtered_sorted_indices 
print 'sorted, filtered x values:\t', x[filtered_sorted_indices] 

输出:

x:       [ 0.8974009 0.30127187 0.71187137 0.04041124] 
sorted indices:    [3 1 2 0] 
indices for x < .5, sorted: [3 1] 
sorted, filtered x values: [ 0.04041124 0.30127187] 
2

发现的x < 0.5x.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]) 
2

屏蔽阵列简明(但也许不是特别有效)

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)]