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

如何用Python(Pandas)多条件筛选交易数据并迁移指定行至Excel新工作表?

使用Pandas处理交易数据的解决方案

以下是实现你需求的完整代码,包含多条件筛选和工作表移动的逻辑:

完整代码

import pandas as pd
from openpyxl import load_workbook

# 1. 加载Excel数据
df = pd.read_excel('交易数据.xlsx')  # 替换为你的文件路径

# 2. 数据预处理:转换时间列格式
df['Trade Time'] = pd.to_datetime(df['Trade Time'])
df['Maturity'] = pd.to_datetime(df['Maturity'])  # 若Maturity为数值型(如天数)则注释此行

# 3. 筛选USD币种的交易
df_usd = df[df['Curr1'] == 'USD'].copy()
non_usd_df = df[df['Curr1'] != 'USD']  # 保留非USD交易

# 4. 按Notional 1分组处理
selected_rows = []
remaining_usd_rows = []

for _, group in df_usd.groupby('Notional 1'):
    # 按交易时间排序
    sorted_group = group.sort_values('Trade Time').reset_index(drop=True)
    
    # 计算相邻交易的时间间隔(分钟)
    sorted_group['time_diff'] = sorted_group['Trade Time'].diff().dt.total_seconds() / 60
    
    # 标记时间间隔在1分钟内的交易集群
    cluster_id = 0
    clusters = [0]
    for i in range(1, len(sorted_group)):
        if sorted_group['time_diff'].iloc[i] > 1:
            cluster_id += 1
        clusters.append(cluster_id)
    sorted_group['cluster'] = clusters
    
    # 处理每个集群
    for _, cluster in sorted_group.groupby('cluster'):
        if len(cluster) < 2:
            remaining_usd_rows.append(cluster)
            continue
        
        # 检查价格价差是否≤0.5%
        min_price = cluster['Price'].min()
        max_price = cluster['Price'].max()
        price_pct_diff = (max_price - min_price) / min_price
        
        if price_pct_diff <= 0.005:
            # 筛选集群中期限最远的行
            max_maturity_row = cluster[cluster['Maturity'] == cluster['Maturity'].max()]
            selected_rows.append(max_maturity_row)
            
            # 保留集群中其他行
            remaining_cluster = cluster[cluster['Maturity'] != cluster['Maturity'].max()]
            remaining_usd_rows.append(remaining_cluster)
        else:
            remaining_usd_rows.append(cluster)

# 5. 合并剩余数据(USD剩余行 + 非USD行)
remaining_df = pd.concat(remaining_usd_rows + [non_usd_df], ignore_index=True)
# 合并选中的期限最远行
selected_df = pd.concat(selected_rows, ignore_index=True)

# 6. 写入Excel的两个工作表
with pd.ExcelWriter('处理后交易数据.xlsx', engine='openpyxl') as writer:
    remaining_df.to_excel(writer, sheet_name='剩余交易', index=False)
    selected_df.to_excel(writer, sheet_name='最远期限交易', index=False)

关键逻辑说明

  • 时间间隔筛选:通过计算相邻交易的时间差,将1分钟内的交易划分为同一集群
  • 价格价差判断:用(最高价-最低价)/最低价计算相对价差,确保不超过0.5%
  • 期限筛选:在符合条件的集群中,选取Maturity值最大(日期最晚/数值最大)的行
  • 数据保留:非USD交易直接保留在原数据集中,符合条件的USD交易除选中行外也保留

注意事项

  1. 若Maturity是数值型(如剩余天数),请注释掉df['Maturity'] = pd.to_datetime(df['Maturity'])这一行
  2. 请将代码中的文件路径替换为你实际的Excel文件路径
  3. 若存在多个行拥有相同的最大Maturity,代码会将这些行全部选中,可根据需求调整筛选逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:37:02