【发布时间】:2015-04-12 21:54:34
【问题描述】:
我有两个测量值,位置和温度,它们以固定的采样率进行采样。某些位置可能在数据中出现多次。现在我想在位置而不是时间上绘制温度。我不想在同一位置显示两个点,而是想用给定位置的平均值替换温度测量值。如何在 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
此解决方案没有考虑到某些位置可能在数据中出现两次以上。要替换所有值,必须多次运行循环。我知道必须有更好的解决方案!
【问题讨论】:
标签: python numpy signal-processing