python - 使用 numpy 将时间平均值恢复为即时值

标签 python python-3.x numpy grib

我有一个平均数量的 3D 字段。现在我正在寻找一种Python式的方法来恢复平均值以获得每个时间戳的瞬时值。注:平均值是从整个周期开始时计算的。它就像滚动平均值,窗口大小适应要平均的值的索引。

为了更好地说明,我给出了一个一维示例:

import numpy as np

input_array = np.array([
       [0.      ],
       [0.5     ],
       [1.      ],
       [1.5     ],
       [2.      ],
       [2.5     ],
       [3.      ],
       [3.25    ],
       [3.333333],
       [3.3     ],
       [3.181818],
       [3.      ],
       [2.769231]
])

exp_result = de_average(input_array)

预期结果exp_result应如下所示:

exp_result= np.array([
       [0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [5],
       [4],
       [3],
       [2],
       [1],
       [0]])

最佳答案

像这样的东西应该可以工作。你的问题与反向累积和问题非常相关,所以我使用给出的解决方案的一部分 here .

from itertools import tee 

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def inverse_cumsum(cumulative):
    """ Inverse an array obtained by cumulative sum
       [1, 3, 6, 10, 15, 21, 28, 36, 45] -> [1, 2, 3, 4, 5, 6, 7, 8, 9] 
    """
    yield cumulative[0]
    for a, b in pairwise(cumulative):
        yield b-a

def inverse_average(a, decimals=1):
   """ Inverse an array averaged (where each entry i is the average up to i) """ 
   deav = inverse_cumsum([a * (i + 1) for i, a in enumerate(a)])
   return np.array(list(deav)).round(decimals)

inverse_average(input_array)

关于python - 使用 numpy 将时间平均值恢复为即时值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66763205/

相关文章:

python - NumPy 和 MATLAB 之间特征向量的微小差异

Python MYSQL 更新

python - Enthought Canopy Mayavi 字体大小错误

python - PIP 随机失败 'Could not find a version that satisfies the requirement' 相同要求.txt

python - 提高 numpy 三角函数运算的性能

python-3.x - PyCharm 单元测试 : AttributeError: module 'enum' has no attribute 'IntFlag'

python - 处理超过最大递归深度

python - 从大量条目创建可迭代列表

python - 在 python 中使用 glob 不会返回最新的文件路径

python - 使用 numpy 元组中的值创建矩阵