Pandas条件语句执行后position列全部返回0问题排查
问题根源
代码的核心问题是循环内的赋值操作是针对整个position列,而非当前遍历到的对应行,每次赋值都会覆盖列内所有已写入的值,最终整列值完全由最后一次循环的判断结果决定,因此会出现全0的异常。
解决方案
1. 修正循环写法(仅适合小数据量场景,大数据量下效率低)
修改赋值逻辑,仅更新当前遍历行的position值:
for bar in range(len(self.data)): if self.data['close'].iloc[bar] > self.data['max_high'].iloc[bar]: self.data['position'].iloc[bar] = 1 elif self.data['close'].iloc[bar] < self.data['max_low'].iloc[bar]: self.data['position'].iloc[bar] = -1 else: self.data['position'].iloc[bar] = 0
2. Pandas向量化操作(推荐,性能更高,同时规避循环易错问题)
直接用numpy.where批量生成目标列,不需要逐行遍历:
import numpy as np self.data['position'] = np.where( self.data['close'] > self.data['max_high'], 1, np.where(self.data['close'] < self.data['max_low'], -1, 0) )
额外说明
你最初遇到的The truth value of a Series is ambiguous报错,本质是最初写判断逻辑时直接对整个Series做布尔判断触发的,使用向量化操作可以直接规避这类问题。
内容的提问来源于stack exchange,提问作者GuyS
相关产品推荐
相关产品推荐

