AI线性填充缺失数据
编辑
6
2025-06-22

提示词
现在我有2022年的CPI月度数据,但1月份的数据是空值,需要进行向后填充,请给出示例代码。
答案
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 生成示例数据(假设日期索引为每月最后一天)
dates = pd.date_range(start='2022-01-31', end='2022-12-31', freq='M')
cpi_data = [280.5, 283.2, 285.1, np.nan, 288.3, 290.0, 292.8, 295.5, 298.2, 302.0, 305.5, 308.0]
df = pd.DataFrame({'CPI': cpi_data}, index=dates)
df.index.name = '日期'
# ==== 数据预处理 ====
# 确保时间序列按日期升序排列(关键步骤)[6](@ref)
df.sort_index(inplace=True)
# ==== 插值填充 ====
# 使用线性插值法填充缺失值(默认沿时间轴插值)[3,7](@ref)
df['CPI_插值'] = df['CPI'].interpolate(method='linear') # 指定插值方法
# ==== 数据验证 ====
print("填充前缺失值数量:", df['CPI'].isnull().sum()) # 预期输出1(4月份缺失)
print("填充后缺失值数量:", df['CPI_插值'].isnull().sum()) # 预期输出0
# ==== 结果可视化 ====
plt.figure(figsize=(12,6))
plt.plot(df.index, df['CPI'], 'ro--', label='原始数据', markersize=8)
plt.plot(df.index, df['CPI_插值'], 'gx-', label='插值填充', markersize=10)
plt.title('2022年CPI月度数据插值填充效果')
plt.xlabel('日期', fontsize=12)
plt.ylabel('CPI指数', fontsize=12)
plt.legend()
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()
另外输出图形,windows中文显示乱码。需要加上
#指定图像样式
plt.style.use('seaborn-v0_8')
#指定字体,防止中文出现乱码,windows系统指定为‘SimHei’
plt.rcParams['font.sans-serif'] = ['SimHei']
#这行代码让中文的负号“-”可以正常显示
plt.rcParams["axes.unicode_minus"]=False
再加一个 print(df.head())
输出结果没毛病,
填充前缺失值数量: 1
填充后缺失值数量: 0
CPI CPI_插值
日期
2022-01-31 280.5 280.5
2022-02-28 283.2 283.2
2022-03-31 285.1 285.1
2022-04-30 NaN 286.7
2022-05-31 288.3 288.3
- 0
- 0
-
赞助
支付宝
微信
-
分享