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

使用np.where筛选多层索引DataFrame符合条件的关联对问题

解决方案

步骤1:修复筛选条件,排除关联值为1.0的条目

你的第一个问题核心是浮点数精度误差——当关联值实际为1.0时,由于浮点数存储的微小偏差,np.less(a, 1.0)可能误判为True。改用np.isclose来精确排除等于1.0的情况:

import numpy as np
import pandas as pd

# 先处理原始数据的缺失值
corr_df = corr_df.dropna()
arr = corr_df.to_numpy()

# 修正筛选逻辑:关联值>0.8 且 与1.0不近似相等
mask = (arr > 0.8) & (~np.isclose(arr, 1.0))
row, col = np.where(mask)

# 生成目标DataFrame,提取datetime、交易对和关联值
selected_corr_df = pd.DataFrame({
    'datetime': [corr_df.index[r][0] for r in row],
    'pair1': [corr_df.index[r][1] for r in row],  # 第二层索引作为交易对1
    'pair2': [corr_df.columns[c] for c in col],    # 列名作为交易对2
    'corr_value': [corr_df.iloc[r, c] for r, c in zip(row, col)]
})

步骤2:简化写法,避免索引提取错误

如果不想手动处理索引,推荐用stack()将DataFrame转为长格式后直接筛选,更简洁且不易出错:

# 多层索引转长格式,自动保留datetime、code(pair1)、列名(pair2)和关联值
long_df = corr_df.stack().reset_index()
long_df.columns = ['datetime', 'pair1', 'pair2', 'corr_value']

# 应用筛选条件(用isclose处理浮点数精度)
selected_corr_df = long_df[
    (long_df['corr_value'] > 0.8) & 
    (~np.isclose(long_df['corr_value'], 1.0))
].reset_index(drop=True)

问题根源说明

  • 浮点数精度:直接用<1.0判断时,部分接近1.0的浮点数(如0.9999999999999999)会被误判为符合条件,np.isclose通过指定容差(默认1e-05)可以精确识别等于1.0的数值。
  • 语法错误:你最初的代码把np.where的条件拆分后用&拼接,这不符合语法规范,正确写法是将整个逻辑条件放在np.where内部。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:05:25