完整代码如下:
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
#读取文件数据
df = pd.read_csv('averageSpeed23.csv',names=['t','g'])
Y0 = df['t']
X0 = df['g']
x=np.array(Y0)
y=np.array(X0)
# statsmodels.api
import statsmodels.api as sm
lowess=sm.nonparametric.lowess
z=lowess(y,x,frac=0.02)
plt.plot(x,y)
plt.title('lowess')
plt.plot(z[:,0],z[:,1],color='r',lw=1)
# Savitzky-Golay filter 平滑
from scipy.signal import savgol_filter
zs=savgol_filter(y, 9, 3) # window size 51, polynomial order 3
plt.figure()
plt.plot(x,y)
plt.title('Savitzky-Golay filter')
plt.plot(x,zs,color='r',lw=1)
plt.show()
结果如下: