在Python中,对数据进行平滑处理可以通过多种方法实现,以下是一些常见的方法及其代码示例:
1. 移动平均(Moving Average)
import numpy as npimport matplotlib.pyplot as plt生成示例数据data = np.array([10, 15, 12, 18, 20, 14, 16, 22, 19, 25])定义移动平均窗口大小window_size = 3计算简单移动平均sma = np.convolve(data, np.ones(window_size)/window_size, mode='valid')plt.plot(data, label='Original Data')plt.plot(sma, label='SMA')plt.legend()plt.show()
2. Savitzky-Golay滤波器
from scipy.signal import savgol_filter假设y是时间序列数据y = np.array([10, 15, 12, 18, 20, 14, 16, 22, 19, 25])调用Savitzky-Golay滤波器y_smooth = savgol_filter(y, 5, 3) window_length=5, polyorder=3plt.plot(y, label='Original Data')plt.plot(y_smooth, label='Savitzky-Golay')plt.legend()plt.show()
3. 插值法
from scipy.interpolate import griddataimport numpy as npimport matplotlib.pyplot as plt创建模拟数据x = np.linspace(-2, 2, 100)y = np.linspace(-2, 2, 100)X, Y = np.meshgrid(x, y)Z = np.sin(X2 + Y2)绘制原始等值线图plt.figure()plt.contour(X, Y, Z, levels=10, colors='k')plt.title('Original Contour')平滑处理xnew = np.linspace(-2, 2, 300)ynew = np.linspace(-2, 2, 300)Xnew, Ynew = np.meshgrid(xnew, ynew)Znew = griddata((x, y), Z, (Xnew, Ynew), method='cubic')plt.figure()plt.contour(Xnew, Ynew, Znew, levels=10, colors='r')plt.title('Smoothed Contour')plt.show()
4. 使用Pandas进行平滑处理
import pandas as pd创建一个包含时间序列数据的DataFramedata = pd.DataFrame({'date': pd.date_range(start='1/1/2020', periods=10), 'value': np.random.randint(1, 100, 10)})data.set_index('date', inplace=True)使用rolling方法进行平滑处理data_smooth = data.rolling(window=3).mean()data.plot(label='Original Data')data_smooth.plot(label='Rolling Mean')plt.legend()plt.show()
以上示例展示了如何使用不同的方法对数据进行平滑处理。您可以根据具体需求选择合适的方法。

