1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import pandas as pd import numpy as np
# 创建示例数据(假设日期为每月最后一天) dates = pd.date_range(start='2022-01-31', periods=12, freq='M') cpi_data = { 'CPI': [np.nan, 280.5, 283.2, 285.1, 288.3, 290.0, 292.8, 295.5, 298.2, 302.0, 305.5, 308.0] } df = pd.DataFrame(cpi_data, index=dates) df.index.name = '日期'
# 执行后向填充 df['CPI'] = df['CPI'].fillna(method='bfill') # 关键填充操作[5,6](@ref)
# 格式化为两位小数 df = df.round(2)
# 检查结果 print(df.head(3))
|