如何在迭代器中屏蔽除每个元素之外的每个元素?

时间:2014-10-11 18:52:23

标签: python numpy mask

我正在尝试创建一个屏蔽数组(或至少填充NaN),该数组仅在第n个(示例中为第8个)位置提供值。该数组应与原始数组的长度相同。

这样做的方法不那么荒谬吗?

b = np.array([[i for i in 7*[np.nan] + [val]] for val in a[::8]]).flatten()[7:]

3 个答案:

答案 0 :(得分:2)

一种方法是使用切片分配:

>>> a
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
       51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63])
>>> b = numpy.array([numpy.NaN] * len(a))
>>> b[::8] = a[::8]
>>> b
array([  0.,  nan,  nan,  nan,  nan,  nan,  nan,  nan,   8.,  nan,  nan,
        nan,  nan,  nan,  nan,  nan,  16.,  nan,  nan,  nan,  nan,  nan,
        nan,  nan,  24.,  nan,  nan,  nan,  nan,  nan,  nan,  nan,  32.,
        nan,  nan,  nan,  nan,  nan,  nan,  nan,  40.,  nan,  nan,  nan,
        nan,  nan,  nan,  nan,  48.,  nan,  nan,  nan,  nan,  nan,  nan,
        nan,  56.,  nan,  nan,  nan,  nan,  nan,  nan,  nan])

答案 1 :(得分:0)

您可以使用生成器表达式来创建"列表"更优雅。

def val_only_on_nth(n, limit):
    for v in xrange(limit):
        if v%n == 0:
            yield v
        else:
            yield np.NaN

并使用np.from_iter将其转换为np数组

b = np.fromiter(val_only_on_nth(8,64))

答案 2 :(得分:0)

这适用于一般情况:

n=8
a=np.random.random((64,))   # example random array to mask
a[np.arange(0,len(a))%n!=0]=np.nan


array([ 0.68756737,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,  0.68577462,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,  0.89002182,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,  0.26135927,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,  0.66857456,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
        0.39230499,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,  0.85367809,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,  0.48642591,         nan,         nan,         nan,
               nan,         nan,         nan,         nan])