python - Numpy:在每个时间步平均多个数据点

标签 python numpy matplotlib scipy

这个问题可能在某个地方有答案,但我找不到答案,所以我会在这里问:

我有一组数据,每个时间步包含多个样本。所以,我基本上有两个数组,“时间”,看起来像:(0,0,0,1,1,1,1,1,2,2,3,4,4,4,4,.. .) 和我的数据,这是每次的值(value)。每个时间步都有随机数量的样本。我想以有效的方式在每个时间步获取数据的平均值。

我准备了以下示例代码来展示我的数据是什么样子的。基本上,我想知道是否有更有效的方法来编写“average_values”函数。

import numpy as np
import matplotlib.pyplot as plt

def average_values(x,y):
    unique_x = np.unique(x)
    averaged_y = [np.mean(y[x==ux]) for ux in unique_x]
    return unique_x, averaged_y

#generate our data
times   = []
samples = []

#we have some timesteps:
for time in np.linspace(0,10,101):

    #and a random number of samples at each timestep:
    num_samples = np.random.random_integers(1,10)

    for i in range(0,num_samples):
        times.append(time)
        samples.append(np.sin(time)+np.random.random()*0.5)

times   = np.array(times)
samples = np.array(samples)

plt.plot(times,samples,'bo',ms=3,mec=None,alpha=0.5)
plt.plot(*average_values(times,samples),color='r')
plt.show()

这是它的样子: enter image description here

最佳答案

执行此操作的通用代码将执行以下操作:

def average_values_bis(x, y):
    unq_x, idx = np.unique(x, return_inverse=True)
    count_x = np.bincount(idx)
    sum_y = np.bincount(idx, weights=y)

    return unq_x, sum_y / count_x

将用于绘图的函数添加到脚本的上方和下方

plt.plot(*average_values_bis(times, samples),color='g')

产生这个输出,红线隐藏在绿线后面:

enter image description here

但是对这两种方法进行计时揭示了使用 bincount 的好处,速度提高了 30 倍:

%timeit average_values(times, samples)
100 loops, best of 3: 2.83 ms per loop

%timeit average_values_bis(times, samples)
10000 loops, best of 3: 85.9 us per loop

关于python - Numpy:在每个时间步平均多个数据点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18727686/

相关文章:

python - 为什么 Azure Active Directory OAuth 适合我而不适合其他人?

python - 在 python 中加载 Analyze 7.5 格式图像

python - OpenCV-车道检测 'numpy.ndarray'错误

python - 将类标签与波形图上的数据点对齐

python - PyTorch optimizer.step() 函数不更新权重

python - 通过 TCP 套接字 python 发送一个字节

在循环外看不到 'for' 循环中声明的 Python 变量

python - Numpy 将一维数组打印为列

python matplotlib堆叠条形图分组在一起

python - matplotlib barh 计划工作时间与实际工作时间