我有两个测量值,位置和温度,它们以固定的采样率采样。某些职位可能会在数据中多次出现。现在我想绘制位置上的温度而不是时间。我不想在同一位置显示两个点,而是要用给定位置的平均值替换温度测量值。如何在python中用numpy很好地完成这项工作?Python Numpy:用平均值替换重复值
我的解决方法到目前为止是这样的:
import matplotlib.pyplot as plt
import numpy as np
# x = Position Data
# y = Temperature Data
x = np.random.permutation([0, 1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9])
y = (x + np.random.rand(len(x)) * 1 - 0.5).round(2)
# Get correct order
idx = np.argsort(x)
x, y = x[idx], y[idx]
plt.plot(x, y) # Plot with multiple points at same location
# Calculate means for dupplicates
new_x = []
new_y = []
skip_next = False
for idx in range(len(x)):
if skip_next:
skip_next = False
continue
if idx < len(x)-1 and x[idx] == x[idx+1]:
new_x.append(x[idx])
new_y.append((y[idx] + y[idx+1])/2)
skip_next = True
else:
new_x.append(x[idx])
new_y.append(y[idx])
skip_next = False
x, y = np.array(new_x), np.array(new_y)
plt.plot(x, y) # Plots desired output
此解决方案不考虑到一些位置可能occoure两次以上的数据。要替换所有值,循环必须多次运行。我知道必须有更好的解决方案!
看起来不错,并产生相同的确切结果是我的解决方案!让我们看看是否有其他人提出了另一个好的解决方案,否则我去接受这个。 – jrast
@jrast当然!没有赶紧。只是对此感到好奇 - 如果您有机会进行基准测试,您是否看到了这种方法的加速?我期望至少有一些加速与此。 – Divakar
我只是将它与@Will给出的解决方案进行比较:我使用了一个包含300000个数据点的数据集,每个位置发生3次(所以有100000个独特位置)。您的解决方案:10个循环,最好3个:每个循环20.6 ms,Will解决方案:1个回路,最好3个:每个回路2.16 s。我认为我的原始解决方案与Will相同,因为它也使用循环。 – jrast