gpt4 book ai didi

python - 对 numpy 数组进行子采样/平均

转载 作者:太空狗 更新时间:2023-10-29 19:33:23 24 4
gpt4 key购买 nike

我有一个带有 float 的 numpy 数组。

我想要的(如果它还不存在的话)是一个函数,它给我一个新数组,该数组包含给定数组中每个 x 点的平均值,例如子采样(与插值相反(?)) .

例如sub_sample(numpy.array([1, 2, 3, 4, 5, 6]), 2) 给出 [1.5, 3.5, 5.5]

例如可以去除剩菜,例如sub_sample(numpy.array([1, 2, 3, 4, 5]), 2) 给出 [1.5, 3.5]

提前致谢。

最佳答案

使用 NumPy 例程你可以尝试类似的东西

import numpy

x = numpy.array([1, 2, 3, 4, 5, 6])

numpy.mean(x.reshape(-1, 2), 1) # Prints array([ 1.5, 3.5, 5.5])

并且只需将 reshape 调用中的 2 替换为您想要平均的项目数。

编辑:假设n 分成x 的长度。如果要将其变成通用函数,则需要包括一些检查。也许是这样的:

def average(arr, n):
end = n * int(len(arr)/n)
return numpy.mean(arr[:end].reshape(-1, n), 1)

这个功能在行动:

>>> x = numpy.array([1, 2, 3, 4, 5, 6])
>>> average(x, 2)
array([ 1.5, 3.5, 5.5])

>>> x = numpy.array([1, 2, 3, 4, 5, 6, 7])
>>> average(x, 2)
array([ 1.5, 3.5, 5.5])

关于python - 对 numpy 数组进行子采样/平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10847660/

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