Python np.add.reduceat的使用

这篇博客介绍了NumPy中`np.add.reduceat()`函数的用法,它用于根据提供的索引进行加法累积操作。通过示例解释了如何利用该函数对数组片段进行求和,并展示了计算过程和结果。博客内容涉及到数组操作、索引选择以及数值计算,适合对NumPy感兴趣的读者学习。
摘要由CSDN通过智能技术生成

np.add.reduceat()

    Parameters
    ----------
    a : array_like
        The array to act on.
    indices : array_like
        Paired indices, comma separated (not colon), specifying slices to
        reduce.
    axis : int, optional
        The axis along which to apply the reduceat.
    dtype : data-type code, optional
        The type used to represent the intermediate results. Defaults
        to the data type of the output array if this is provided, or
        the data type of the input array if no output array is provided.
    out : ndarray, None, or tuple of ndarray and None, optional
        A location into which the result is stored. If not provided or None,
        a freshly-allocated array is returned. For consistency with
        ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
        1-element tuple.
    
        .. versionchanged:: 1.13.0
           Tuples are allowed for keyword argument.
    
    Returns
    -------
    r : ndarray
        The reduced values. If `out` was supplied, `r` is a reference to
        `out`.

 np.add.reduceat()的使用

demo = np.add.reduceat(np.arange(8),[0, 4, 1, 5, 2, 6, 3, 7])[::2]

 上例即:demo = np.add.redrceat([0, 1, 2, 3, 4, 5, 6, 7], [0, 4, 1, 5, 2, 6, 3, 7])[::2]

令a = [0, 1, 2, 3, 4, 5, 6, 7], b = [0, 4, 1, 5, 2, 6, 3, 7]

计算过程如下:

        b[i+1] > b[i], demo[i]  = np.reduce(add, a[b[i]] : a[b[i+1]]),如:4 > 0, demo[0] = 0 + 1 + 2 + 3

        b[i+1] < b[i], demo[i] = np.reduce(add, a[b[i]]),如:1 < 4, demo[1] = 4

 结果如下:

>> demo = np.add.redrceat([0, 1, 2, 3, 4, 5, 6, 7], [0, 4, 1, 5, 2, 6, 3, 7])
>> print(demo)
[ 6  4 10  5 14  6 18  7]
>> demo_ = np.add.redrceat([0, 1, 2, 3, 4, 5, 6, 7], [0, 4, 1, 5, 2, 6, 3, 7])[::2]
>> print(demo_)
[ 6 10 14 18]

#[::2] => list[start:end:step]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值