Numpy 数组索引中元组的部分解包

Chi*_*kus 4 python numpy

为了解决一个只能逐个元素出现的问题,我需要将 NumPy 的元组索引与显式切片相结合。

def f(shape, n):
    """
    :param shape: any shape of an array
    :type shape: tuple
    :type n: int
    """
    x = numpy.zeros( (n,) + shape )
    for i in numpy.ndindex(shape):                   # i = (k, l, ...)
        x[:, k, l, ...] = numpy.random.random(n)
Run Code Online (Sandbox Code Playgroud)

x[:, *i]结果为 aSyntaxError并被x[:, i]解释为numpy.array([ x[:, k] for k in i ])。Unfortunally这是不可能有n维作为最后一个(x = numpy.zeros(shape+(n,))x[i] = numpy.random.random(n)由于进一步使用的)x

编辑:这里有一些例子希望在评论中。

>>> n, shape = 2, (3,4)
>>> x = np.arange(24).reshape((n,)+(3,4))
>>> print(x) 
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]]])
>>> i = (1,2)
>>> print(x[ ??? ])    # '???' expressed by i with any length is the question
array([ 6, 18])
Run Code Online (Sandbox Code Playgroud)

tob*_*s_k 5

如果我正确理解了这个问题,那么您有一个多维 numpy 数组,并希望通过将:切片与 tuple 中的一些其他索引组合来对其进行索引i

numpy 数组的索引是一个元组,因此您基本上可以将这些“部分”索引组合为一个元组并将其用作索引。一个天真的方法可能看起来像这样

x[ (:,) + i ] = numpy.random.random(n) # does not work
Run Code Online (Sandbox Code Playgroud)

但这会产生语法错误。而不是:,您必须使用slice内置函数。

x[ (slice(None),) + i ] = numpy.random.random(n)
Run Code Online (Sandbox Code Playgroud)