2015-09-30 40 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)]