numpy.apply_along_axis

numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)[源代码]

沿给定轴对一维切片应用函数。

执行 func1d(a, *args, **kwargs) 在哪里? func1d 在一维数组上操作 a 是一个一维切片 arr 沿着 axis .

这相当于(但比)以下使用 ndindexs_ ,设置每个 iijjkk 到一组索引:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        f = func1d(arr[ii + s_[:,] + kk])
        Nj = f.shape
        for jj in ndindex(Nj):
            out[ii + jj + kk] = f[jj]

等效地,消除内环,这可以表示为:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
参数
func1d函数(m,)->(nj…)

此函数应接受一维数组。它应用于 arr 沿指定轴。

axis整数

沿哪个轴 arr 切片。

arrNdarray(ni…,m,nk…)

输入数组。

args任何

附加参数 func1d .

kwargs任何

的其他命名参数 func1d .

1.9.0 新版功能.

返回
outNdarray(镍…,新泽西…,NK…)

输出数组。形状 out 与…的形状相同 arr 除了沿着 axis 尺寸。此轴被删除,并替换为与返回值的形状相同的新尺寸。 func1d . 所以如果 func1d 返回标量 out 尺寸比 arr .

参见

apply_over_axes

在多个轴上重复应用函数。

实例

>>> def my_func(a):
...     """Average first and last element of a 1-D array"""
...     return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2.,  5.,  8.])

对于返回一维数组的函数,在 outarr 是一样的 arr .

>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
       [3, 4, 9],
       [2, 5, 6]])

对于返回更高维数组的函数,这些维将插入到 axis 尺寸。

>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(np.diag, -1, b)
array([[[1, 0, 0],
        [0, 2, 0],
        [0, 0, 3]],
       [[4, 0, 0],
        [0, 5, 0],
        [0, 0, 6]],
       [[7, 0, 0],
        [0, 8, 0],
        [0, 0, 9]]])