NumPy:从阈值之上和之下的蒙版2D阵列中查找已排序的索引

时间:2011-08-23 00:06:50

标签: python numpy indices

我有一个2D掩码值数组,我需要从最低到最高排序。例如:

import numpy as np

# Make a random masked array
>>> ar = np.ma.array(np.round(np.random.normal(50, 10, 20), 1),
                     mask=np.random.binomial(1, .2, 20)).reshape((4,5))
>>> print(ar)
[[-- 51.9 38.3 46.8 43.3]
 [52.3 65.0 51.2 46.5 --]
 [56.7 51.1 -- 38.6 33.5]
 [45.2 56.8 74.1 58.4 56.4]]

# Sort the array from lowest to highest, with a flattened index
>>> sorted_ind = ar.argsort(axis=None)
>>> print(sorted_ind)
[14  2 13  4 15  8  3 11  7  1  5 19 10 16 18  6 17  0 12  9]

但是对于排序的索引,我需要将它们分成两个简单的子集:小于或等于大于或等于给定的数据。此外,我不需要屏蔽值,需要删除它们。例如,对于datum = 51.1,如何将sorted_ind过滤到datum以上的10个索引以及下面的8个值? (注意:由于或等于逻辑标准,有一个共享索引。可以从分析中删除3个掩码值)。我需要保留展平的索引位置,因为我稍后会使用np.unravel_index(ind, ar.shape)

2 个答案:

答案 0 :(得分:5)

使用where:

import numpy as np
np.random.seed(0)
# Make a random masked array
ar = np.ma.array(np.round(np.random.normal(50, 10, 20), 1),
                     mask=np.random.binomial(1, .2, 20)).reshape((4,5))
# Sort the array from lowest to highest, with a flattened index
sorted_ind = ar.argsort(axis=None)

tmp = ar.flatten()[sorted_ind]
print sorted_ind[np.ma.where(tmp<=51.0)]
print sorted_ind[np.ma.where(tmp>=51.0)]

但由于tmp已排序,您可以使用np.searchsorted():

tmp = ar.flatten()[sorted_ind].compressed() # compressed() will delete all invalid data.
idx = np.searchsorted(tmp, 51.0)
print sorted_ind[:idx]
print sorted_ind[idx:len(tmp)]

答案 1 :(得分:3)

准备:

>>> ar = np.ma.array(np.round(np.random.normal(50, 10, 20), 1),
                     mask=np.random.binomial(1, .2, 20)).reshape((4,5))
>>> print(ar)
[[59.9 51.3 -- 19.7 --]
 [59.1 57.2 48.6 49.8 46.3]
 [51.1 61.6 36.9 52.2 51.7]
 [37.9 -- -- 53.1 57.5]]
>>> sorted_ind = ar.argsort(axis=None)
>>> sorted_ind
array([ 3, 12, 15,  9,  7,  8, 10,  1, 14, 13, 18,  6, 19,  5,  0, 11,  4,
        2, 16, 17])

然后新的东西

>>> flat = ar.flatten()
>>> leq_ind = filter(lambda x: flat[x] <= 51.1, sorted_ind)
>>> leq_ind
[3, 12, 15, 9, 7, 8, 10]
>>> geq_ind = filter(lambda x: flat[x] >= 51.1, sorted_ind)
>>> geq_ind
[10, 1, 14, 13, 18, 6, 19, 5, 0, 11]
相关问题