You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于BUY/SELL列值从Dataframe创建动态子表的技术需求

按BUY-SELL间隔拆分DataFrame为动态子表的实现方案

核心逻辑

从DataFrame中提取有效BUY-SELL配对:每个配对以一个BUY为起点,跳过中间所有后续BUY,找到第一个在该BUY之后的SELL作为终点;完成一对后,从该SELL之后的下一个BUY开始重复流程,最终生成多个长度动态的子表。

代码实现(基于Pandas)

import pandas as pd

# 假设你的数据存储在df中,Signal列是标记BUY/SELL的列
# 1. 提取所有BUY和SELL的索引位置
buy_indices = df[df['Signal'] == 'BUY'].index.tolist()
sell_indices = df[df['Signal'] == 'SELL'].index.tolist()

# 2. 筛选有效的BUY-SELL配对
valid_pairs = []
buy_ptr, sell_ptr = 0, 0

while buy_ptr < len(buy_indices) and sell_ptr < len(sell_indices):
    current_buy = buy_indices[buy_ptr]
    current_sell = sell_indices[sell_ptr]
    
    if current_buy < current_sell:
        # 检查下一个BUY是否在当前SELL之前,若是则跳过当前BUY
        if buy_ptr + 1 < len(buy_indices) and buy_indices[buy_ptr + 1] < current_sell:
            buy_ptr += 1
        else:
            valid_pairs.append((current_buy, current_sell))
            buy_ptr += 1
            sell_ptr += 1
    else:
        # 当前SELL在BUY之前,跳过该SELL
        sell_ptr += 1

# 3. 生成子表列表
sub_tables = [df.loc[start:end].copy() for start, end in valid_pairs]

# 查看结果示例
for idx, sub_table in enumerate(sub_tables, 1):
    print(f"子表 {idx}:")
    print(sub_table)
    print("="*60)

代码说明

  • 双指针法遍历BUY和SELL索引,确保只保留不被中间BUY打断的有效配对
  • 用df.loc[start:end]按索引切片生成子表,copy()避免原DataFrame被修改
  • 最终sub_tables列表中存储了所有符合要求的子表,可按需调用或保存

内容的提问来源于stack exchange,提问作者La Myass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 08:47:32