Pandas基于多if-else条件创建布尔新列及报错解决
报错原因拆解
- 链式比较不支持Pandas Series:Python原生的
15 <= df.close < 30会尝试对整列Series返回单个布尔值,触发The truth value of a Series is ambiguous报错。必须拆分为两个独立条件用位与符&连接,且每个条件加括号避免运算符优先级问题。 - 滑动最大值计算逻辑错误:你之前使用的
df.formula[-4:-1].max()、tail(3)仅会计算全表最后3行的固定最大值,没有对每一行单独计算其前3行的滑动最大值,需要用rolling滑动窗口函数实现逐行计算。
正确实现代码
import pandas as pd import numpy as np # 预计算每一行对应的前3行formula列最大值(匹配原逻辑中df.formula[-4:-1].max()的规则) # rolling(3)指定窗口大小为3,shift(1)前移一位排除当前行,仅取当前行之前的3行数据计算 df['pre_3_formula_max'] = df['formula'].rolling(3).max().shift(1) # 定义价格区间条件和对应阈值 cond_list = [ df['close'] >= 30, (df['close'] >= 15) & (df['close'] < 30), (df['close'] >= 5) & (df['close'] < 15), (df['close'] >= 2.5) & (df['close'] < 5) ] threshold_list = [5, 3, 1, 0.5] # 生成cond17布尔列,价格低于2.5时默认阈值为0.02 df['cond17'] = np.select( cond_list, [df['pre_3_formula_max'] <= t for t in threshold_list], default=df['pre_3_formula_max'] <= 0.02 ) # 可选:删除中间计算列 df.drop('pre_3_formula_max', axis=1, inplace=True)
补充说明
前3行因没有足够的前置数据,cond17会返回NaN,符合formula列前几行存在空值的特性,若需填充这部分空值可额外调用fillna()方法指定默认布尔值。
内容的提问来源于stack exchange,提问作者Garrad2810
相关产品推荐
相关产品推荐

