对除一个轴之外的所有轴求和

Foo*_*Bar 4 python numpy sum

有好几次,我处理过ND数组,比如

foo = np.arange(27).reshape((3,3, 3))
Run Code Online (Sandbox Code Playgroud)

然后我会有一个维度,我想在下一个操作中保留变量。假设下一个操作是mean,在这种情况下

preserveAxis = 1
desiredOutcome = foo.mean(axis=0).mean(axis=1)
Run Code Online (Sandbox Code Playgroud)

前一个是我想要的结果,因为我首先在第 0 个轴上取平均值,然后在第 2 个轴上取平均值(在初始操作后已成为第一个轴)。也就是说,我已经在轴 0 和 2 上完成了操作,但保留了轴 1

这种类型的程序很麻烦,而且最重要的是不通用。我正在寻找一种通用方法来保留一个轴,但对所有其他轴进行求和/平均值。我怎样才能最好地实现这一目标,最好是在 以内numpy

Div*_*kar 6

这是一个推广到 n 维情况的简化方法ufuncs-

def reduce_skipfew(ufunc, foo, preserveAxis=None):
    r = np.arange(foo.ndim)   
    if preserveAxis is not None:
        preserveAxis = tuple(np.delete(r, preserveAxis))
    return ufunc(foo, axis=preserveAxis)
Run Code Online (Sandbox Code Playgroud)

样本运行 -

In [171]: reduce_skipfew(np.mean, foo, preserveAxis=1)
Out[171]: array([10., 13., 16.])

In [172]: foo = np.arange(27).reshape((3,3, 3))

In [173]: reduce_skipfew(np.mean, foo, preserveAxis=1)
Out[173]: array([10., 13., 16.])

In [174]: reduce_skipfew(np.sum, foo, preserveAxis=1)
Out[174]: array([ 90, 117, 144])

# preserve none i.e. sum all
In [175]: reduce_skipfew(np.sum, foo, preserveAxis=None)
Out[175]: 351

# preserve more than one axis
In [176]: reduce_skipfew(np.sum, foo, preserveAxis=(0,2)) 
Out[176]: 
array([[ 9, 12, 15],
       [36, 39, 42],
       [63, 66, 69]])
Run Code Online (Sandbox Code Playgroud)