python--------------apply_along_axis()函数

 apply_along_axis()函数的具体代码如下所示:

def apply_along_axis(func1d, axis, arr, *args, **kwargs):
    """
    沿指定轴对数组进行切片,并将切片应用于给定的函数。

    执行 `func1d(a, *args)`,其中 `func1d` 操作在一维数组 `a` 上,
    而 `a` 是沿着 `axis` 的数组切片。

    参数
    ----------
    func1d : 函数
        该函数应该接受一维数组。它将被应用于沿着指定轴的数组切片。
    axis : 整数
        对数组进行切片的轴。
    arr : ndarray
        输入数组。
    args : 任意
        传递给 `func1d` 的额外参数。
    kwargs : 任意
        传递给 `func1d` 的额外命名参数。

        .. versionadded:: 1.9.0

    返回
    -------
    apply_along_axis : ndarray
        输出数组。`outarr` 的形状与 `arr` 的形状相同,除了沿着 `axis` 维度。
        这个轴被移除,并替换为与 `func1d` 返回值的形状相等的新维度。
        因此,如果 `func1d` 返回一个标量,`outarr` 将比 `arr` 少一个维度。

    参见
    --------
    apply_over_axes : 重复地在多个轴上应用函数。
    """
    # 处理负数轴
    arr = asanyarray(arr)
    nd = arr.ndim
    axis = normalize_axis_index(axis, nd)

    # 将轴放在最后
    in_dims = list(range(nd))
    inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis])

    # 计算迭代轴的索引,并添加一个尾随的省略号,以防止零维数组变成标量,从而修复了 gh-8642
    inds = ndindex(inarr_view.shape[:-1])
    inds = (ind + (Ellipsis,) for ind in inds)

    # 在第一个元素上调用函数
    try:
        ind0 = next(inds)
    except StopIteration:
        raise ValueError('当任何迭代维度为0时,无法应用 apply_along_axis')
    res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))

    # 创建一个缓冲区以存储 func1d 的评估结果。
    # 删除请求的轴,并在最后添加新的轴。
    # 布局使得每次写入都是连续的。
    # 对于元组索引 inds,buff[inds] = func1d(inarr_view[inds])
    buff = zeros(inarr_view.shape[:-1] + res.shape, res.dtype)

    # 轴的排列,以便 out = buff.transpose(buff_permute)
    buff_dims = list(range(buff.ndim))
    buff_permute = (
        buff_dims[0 : axis] +
        buff_dims[buff.ndim-res.ndim : buff.ndim] +
        buff_dims[axis : buff.ndim-res.ndim]
    )

    # 矩阵有一个讨厌的 __array_prepare__ 和 __array_wrap__
    if not isinstance(res, matrix):
        buff = res.__array_prepare__(buff)

    # 保存第一个结果,然后计算并保存所有剩下的结果
    buff[ind0] = res
    for ind in inds:
        buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs))

    if not isinstance(res, matrix):
        # 包装数组,以保留子类
        buff = res.__array_wrap__(buff)

        # 最后,将插入的轴旋转回它们应该在的位置
        return transpose(buff, buff_permute)

    else:
        # 矩阵首先必须进行转置,因为它们会折叠维度!
        out_arr = transpose(buff, buff_permute)
        return res.__array_wrap__(out_arr)

 函数具体的作用可以用如下几个案例来说明:

import numpy as np

def function(a):
    return (a[0] + a[-1]) * 3
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
c = np.apply_along_axis(function, 0, b)
d = np.apply_along_axis(function, 1, b)
print(f"c和d得到的结果分别为:", c, d)

e = np.array([[8, 1, 7, 15], [4, 8, 9, 45], [5, 2, 33, 6]])
f = np.apply_along_axis(sorted, -1, e)  # 排序

print(f"f得到的结果为: ", f)

g = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
h = np.apply_along_axis(np.diag, -1, b)
print(f"h得到的结果为: ", h)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长沙有肥鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值