减少numpy数组以绘制图表。

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

这个解决方案比第一个慢。那么对于这个问题,最好的解决方案是什么?

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

接下来,您可以使用np.histogram在5秒间隔内计算分组总和:

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

如果您想要平均值而不是总和,请删除权重并使用箱子计数:
means = sums / np.histogram(t, t_bins)][0]

这个方法类似于这个答案中的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接