gpt4 book ai didi

Python。 nwise numpy 数组迭代

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:48 24 4
gpt4 key购买 nike

是否有一个 numpy 函数可以有效地允许 nwise迭代?

# http://seriously.dontusethiscode.com/2013/04/28/nwise.html
from itertools import tee, islice
nwise = lambda xs, n=2: zip(*(islice(xs, idx, None) for idx, xs in enumerate(tee(xs, n))))

例如。对元素应用均值?获得移动平均线?

最佳答案

通用:

import numpy as np
from numpy.lib.stride_tricks import as_strided

def moving_slice(a, k):
a = a.ravel()
return as_strided(a, (a.size - k + 1, k), 2 * a.strides)

平均移动效果更好:

def moving_avg(a, k):
ps = np.cumsum(a)
return (ps[k-1:] - np.r_[0, ps[:-k]]) / k

示例:

a = np.arange(10)

moving_avg(a, 4)
# array([ 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5])

ms = moving_slice(a, 4)
ms
# array([[0, 1, 2, 3],
# [1, 2, 3, 4],
# [2, 3, 4, 5],
# [3, 4, 5, 6],
# [4, 5, 6, 7],
# [5, 6, 7, 8],
# [6, 7, 8, 9]])

# no data are copied:
a[4] = 0
ms
# array([[0, 1, 2, 3],
# [1, 2, 3, 0],
# [2, 3, 0, 5],
# [3, 0, 5, 6],
# [0, 5, 6, 7],
# [5, 6, 7, 8],
# [6, 7, 8, 9]])

关于Python。 nwise numpy 数组迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47506663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com