Python如何判断三点共线 pandas向量化替代嵌套循环方案
Pandas向量化实现容差范围内共线点位识别
问题描述
- 此前尝试过基于三角形面积判定点位共线的方案,因无法适配后续步骤的计算需求,无法投入使用
- 初始实现思路为嵌套循环逻辑:先取两个基准点计算连线斜率,基于斜率推导后续各点位的预期价格,若点位实际价格与预期价格的偏差在±0.5%相对偏差容差范围内,即可判定为共线点位
- 目前已完成第一层循环的相邻点斜率计算,但第二层循环的预期价格比对逻辑编写受阻,需要更简便的共线点位识别方案,优先考虑向量化实现替代低效嵌套循环
- 固定比对规则:按索引从小到大依次取两个点作为基准点对,仅校验索引位置在两个基准点之后的所有点是否符合共线要求,遍历组合包括:
- 索引0、1点对,校验索引2、3、4点
- 索引0、2点对,校验索引3、4点
- 索引0、3点对,校验索引4点
- 索引1、2点对,校验索引3、4点
- 剩余点对按相同规则依次遍历
测试数据集
import pandas as pd initial_data = {'index': [4, 17, 24, 36, 42], 'High': [805.000000, 1094.939941, 1243.489990, 1201.949951, 1172.839966], } test = pd.DataFrame(initial_data) slope_data = {'index': [4, 17, 24, 36, 42], 'High': [805.000000, 1094.939941, 1243.489990, 1518.7, 1172.839966], 'Slope': [0, 22.30307, 21.22144, 22.93417, -57.64334], }
已编写的未完成代码片段
for i in range(len(test)): #test.loc[:,'slope'] = (test.loc[i,'High'] - test.loc[i,'High']) / (test.loc[i,'index'] - test.loc[i,'index']) test['slope'] = round((test['High']-test['High'].shift(1)) / (test['index']-test['index'].shift(1)),8) print(test) for j in range(len(test)): exp_price = (test['High'].shift(1) + (test['slope']*(test['index']-test['index'].shift(j)))) # 若j点对应的预期价格与i点实际High值偏差在±0.5%范围内,即找到共线点 # print(values) test['result'] = values print(test)
内容的提问来源于stack exchange,提问作者Artrade
相关产品推荐
相关产品推荐

