![image]()
import pandas as pd
# 读取Excel文件
file_path = 'F:/lianxi/dry_index_rank样条法4-10月.xlsx' # 替换为你的Excel文件路径
df = pd.read_excel(file_path)
# 确保数据按station、year、month排序
df.sort_values(['station', 'year', 'month'], inplace=True)
# 创建新的滞后列
lag_columns = ['PA', 'SPI1', 'MI', 'MCI', 'RH']
new_columns = [col + '滞后1个月' for col in lag_columns]
# 分组并应用滞后操作
for col, new_col in zip(lag_columns, new_columns):
df[new_col] = df.groupby(['station', 'year'])[col].shift(-1)
# 处理跨年的情况(12月滞后到次年1月)
for station in df['station'].unique():
# 获取该站点的所有数据
station_mask = df['station'] == station
station_data = df[station_mask].copy()
# 找出每年的12月数据
dec_data = station_data[station_data['month'] == 12]
for _, row in dec_data.iterrows():
year = row['year']
next_year_data = station_data[(station_data['year'] == year + 1) & (station_data['month'] == 1)]
if not next_year_data.empty:
for col, new_col in zip(lag_columns, new_columns):
# 找到当前12月数据的索引
current_idx = row.name
# 找到次年1月数据的值
next_jan_value = next_year_data[col].values[0]
# 赋值给12月数据的滞后列
df.at[current_idx, new_col] = next_jan_value
# 保存回原Excel文件
df.to_excel(file_path, index=False)
print("处理完成,结果已写回原Excel文件")