如何将DataFrame某列值与另一列之前的所有值比较生成新列?
问题:生成符合特定逻辑的DataFrame列x
原始DataFrame
import pandas as pd df = pd.DataFrame( { 'high': [100, 102, 120, 150, 125, 115], 'target': [99, 105, 118, 108, 140, 141] } )
预期输出
high target x 0 100 99 99 1 102 105 99 2 120 118 118 3 150 108 118 4 125 140 118 5 115 141 108
生成列x的逻辑
对每行的high值,需与当前行及之前所有行的target值比较,找出其中小于等于high的最大值,作为该行x的值:
- 第0行:
high=100,仅对比target=99,结果为99 - 第1行:
high=102,对比target=[99,105],≤102的最大值是99 - 第2行:
high=120,对比target=[99,105,118],≤120的最大值是118 - 第3行:
high=150,对比target=[99,105,118,108],≤150的最大值是118 - 第4行:
high=125,对比target=[99,105,118,108,140],≤125的最大值是118 - 第5行:
high=115,对比所有target值,≤115的最大值是108
尝试过的错误代码
import numpy as np bins = df.target.sort_values(ascending=True).to_list() bins = bins + [np.inf] labels = bins[:-1] df['x'] = pd.cut(df.high, include_lowest=True, right=False, labels=labels, bins=bins)
该方法错误原因:使用了全局排序的target作为分箱依据,没有遵循“仅对比当前行及之前的target”的规则,导致结果不符合预期。
解决方案
方法1:逐行索引处理(直观易懂)
def calculate_x(row_index, df): # 获取当前行及之前的所有target值 past_targets = df.loc[:row_index, 'target'] # 筛选出小于等于当前high的target值 valid_targets = past_targets[past_targets <= df.loc[row_index, 'high']] # 返回最大值 return valid_targets.max() # 为每行计算x值 df['x'] = df.index.map(lambda idx: calculate_x(idx, df))
方法2:累积数组优化(效率更高)
# 生成每行对应的累积target列表(到当前行为止的所有target) cumulative_targets = df['target'].expanding().apply(lambda arr: arr.values, raw=True).tolist() # 遍历每行,计算符合条件的最大值 df['x'] = [max(t for t in targets if t <= high) for high, targets in zip(df['high'], cumulative_targets)]
两种方法都能准确生成符合要求的x列,其中方法2在数据量较大时效率更优。
内容的提问来源于stack exchange,提问作者AmirX
相关产品推荐
相关产品推荐

