这里介绍的是用于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)
示例运行 -
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]])