我有兩個測量值,位置和溫度,它們以固定的採樣率採樣。某些職位可能會在數據中多次出現。現在我想繪製位置上的溫度而不是時間。我不想在同一位置顯示兩個點,而是要用給定位置的平均值替換溫度測量值。如何在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