好几次,我都处理过ND数组,例如
foo = np.arange(27).reshape((3,3, 3))
,然后我有一个维度,我要在该维度上保留下一个操作中的变量。假设下一个操作是mean
,在这种情况下
preserveAxis = 1
desiredOutcome = foo.mean(axis=0).mean(axis=1)
前一个是我想要的结果,因为我首先在第0轴上取平均值,然后在第2轴(在初次操作后变成第1个)上取平均值。也就是说,我已经在轴0和2上完成了操作,但保留了轴1 。
这种过程很麻烦,最重要的是不是通用的。我正在寻找一种通用方法来保留一个轴,但求和/求平均值。我如何才能最好地做到这一点,最好在numpy
内?
答案 0 :(得分:3)
您可以将元组用作axis参数:
foo.mean(axis=(0, 2))
如果数组的维数可变和/或保留的维数可以变化,则可能会有些棘手。参见@Divakar的答案。
答案 1 :(得分:3)
这里是一种普遍适用于n-dim减数的案例,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]])