我有一个平均数量的 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/