Pandas如何按规则更新point列,x/y非空时后续point值按指定逻辑调整
实现思路
我们通过逐行遍历DataFrame维护状态变量的方式实现规则,核心逻辑是标记所有x/y非空的行,触发下一行point值复用,之后按指定步长和区间规则递加值即可。
完整可运行代码
import pandas as pd import numpy as np # 读取数据 df = pd.read_csv("data.csv") new_points = [] # 存储上一行最终point值 prev_point = df.loc[0, 'point'] # 标记下一行是否需要复用当前point值 need_repeat = False for idx, row in df.iterrows(): if idx == 0: new_points.append(prev_point) # 首行x/y非空则标记下一行复用 if not np.isnan(row['x']) or not np.isnan(row['y']): need_repeat = True continue if need_repeat: current_point = prev_point need_repeat = False else: # 按区间规则计算当前point值 if prev_point < 0.6: current_point = round(prev_point + 0.1, 1) elif prev_point == 0.6: current_point = 1.1 elif prev_point < 1.6: current_point = round(prev_point + 0.1, 1) else: current_point = 0.1 new_points.append(current_point) prev_point = current_point # 检查当前行是否触发下一行复用 if not np.isnan(row['x']) or not np.isnan(row['y']): need_repeat = True # 替换原point列 df['point'] = new_points # 输出验证 print(df)
运行上述代码得到的结果和你给出的期望输出完全一致。
内容的提问来源于stack exchange,提问作者python noob
相关产品推荐
相关产品推荐

