3

我想在我的 python 应用程序中绘制图表,但源 numpy 数组太大而无法执行此操作(大约 1'000'000+)。我想取相邻元素的平均值。第一个想法是用 C++ 风格来做:

step = 19000 # every 19 seconds (for example) make new point with neam value
dt = <ordered array with time stamps>
value = <some random data that we want to draw>

index = dt - dt % step
cur = 0
res = []

while cur < len(index):
    next = cur
    while next < len(index) and index[next] == index[cur]:
        next += 1
    res.append(np.mean(value[cur:next]))
    cur = next

但这个解决方案工作得很慢。我试着这样

step = 19000 # every 19 seconds (for example) make new point with neam value
dt = <ordered array with time stamps>
value = <some random data that we want to draw>

index = dt - dt % step
data = np.arange(index[0], index[-1] + 1, step)
res = [value[index == i].mean() for i in data]
pass

此解决方案比第一个解决方案慢。这个问题的最佳解决方案是什么?

4

1 回答 1

3

np.histogram可以提供任意箱的总和。如果您有时间序列,例如:

import numpy as np

data = np.random.rand(1000)          # Random numbers between 0 and 1
t = np.cumsum(np.random.rand(1000))  # Random time series, from about 1 to 500

然后您可以使用以下方法计算 5 秒间隔内的合并总和np.histogram

t_bins = np.arange(0., 500., 5.)       # Or whatever range you want
sums = np.histogram(t, t_bins, weights=data)[0]

如果您想要平均值而不是总和,请删除权重并使用 bin 计数:

means = sums / np.histogram(t, t_bins)][0]

此方法类似于此答案中的方法。

于 2012-06-20T10:27:33.003 回答