Python Pandas基于历史序列值比较逻辑生成条件新列的实现问题
原代码核心问题
- 循环逻辑错误:
for i in df是遍历DataFrame的列名,而非逐行处理数据行,完全偏离逐行计算的需求 - 违反数据使用约束:原有判断逻辑基于全表温度值匹配,会引用当前行之后的后续数据,不符合「仅使用当前行之前历史值」的要求
正确实现代码
import numpy as np import pandas as pd # 构建测试数据集 df = pd.DataFrame({'temperature': [15, 26, 24, 23, 26, 29, 25, 24, 19, 16, 15]}) record = [] for i in range(len(df)): curr_temp = df.loc[i, 'temperature'] # 仅截取当前行索引之前的所有历史温度值 hist_temps = df.loc[:i-1, 'temperature'] # 首行无历史数据,直接填充NaN if len(hist_temps) == 0: record.append(np.nan) continue # 筛选历史中小于当前温度的记录,取索引最大(距离最近)的目标值位置 smaller_temps = hist_temps[hist_temps < curr_temp] if smaller_temps.empty: record.append(np.nan) continue t_idx = smaller_temps.index.max() target_val = df.loc[t_idx, 'temperature'] # 校验目标值的前序值:无前置索引或前序值不大于目标值时,填充NaN if t_idx == 0 or df.loc[t_idx - 1, 'temperature'] <= target_val: record.append(np.nan) else: record.append(target_val) df['record'] = record print(df)
运行输出结果
temperature record 0 15 NaN 1 26 NaN 2 24 NaN 3 23 NaN 4 26 23.0 5 29 23.0 6 25 23.0 7 24 23.0 8 19 NaN 9 16 NaN 10 15 NaN
注:输出中数值自动带小数点是因为
np.nan为浮点型,与预期结果的数值逻辑完全一致。
内容的提问来源于stack exchange,提问作者windwalker
相关产品推荐
相关产品推荐

