如何高效删除Pandas DataFrame中被支配行(所有值均小于等于另一行)
非支配行过滤高效实现方案
核心思路
这个需求本质是提取数据集的帕累托最优前沿行,即不存在任意其他行在所有维度上都优于/等于当前行,且至少一个维度严格优于当前行。我们采用numpy向量化操作替代原生Python循环,大幅提升运算效率,同时支持自定义阈值适配浮点精度误差。
可直接复用的实现代码
基础版本(适配数千行/列场景)
import pandas as pd import numpy as np def filter_dominated_rows(df, threshold=1e-4): arr = df.values n_rows = arr.shape[0] # 初始化标记数组,True表示对应行为非支配行 is_non_dominated = np.ones(n_rows, dtype=bool) for i in range(n_rows): # 已经被判定为支配的行跳过对比 if not is_non_dominated[i]: continue # 广播对比:所有行各维度是否小于等于当前行(带浮点阈值) all_less_or_equal = np.all(arr <= arr[i] + threshold, axis=1) # 广播对比:所有行是否存在至少一个维度严格小于当前行(带浮点阈值) any_less = np.any(arr < arr[i] - threshold, axis=1) # 同时满足两个条件的行即为被当前行支配的行 dominated = all_less_or_equal & any_less # 排除当前行自身 dominated[i] = False # 更新标记数组 is_non_dominated[dominated] = False return df[is_non_dominated]
优化版本(超大数据集可选)
通过预排序优先处理高值行,更快标记被支配样本,减少无效对比:
def filter_dominated_rows_optimized(df, threshold=1e-4, sort_col=0): # 按指定列降序排序,保留原始索引 df_sorted = df.sort_values(by=sort_col, ascending=False).reset_index(drop=False) arr = df_sorted.drop(columns='index').values n_rows = arr.shape[0] is_non_dominated = np.ones(n_rows, dtype=bool) for i in range(n_rows): if not is_non_dominated[i]: continue all_less_or_equal = np.all(arr <= arr[i] + threshold, axis=1) any_less = np.any(arr < arr[i] - threshold, axis=1) dominated = all_less_or_equal & any_less dominated[i] = False is_non_dominated[dominated] = False # 恢复原始索引顺序 res = df_sorted[is_non_dominated].set_index('index').sort_index() res.index.name = None return res
测试验证
# 测试用例 df = pd.DataFrame([[6,5,4,3,8], [6,5,4,3,6], [1,1,3,9,5], [0,1,2,7,4], [2, 0, 0, 4, 0]]) print(filter_dominated_rows(df))
输出结果:
0 1 2 3 4 0 6 5 4 3 8 2 1 1 3 9 5 4 2 0 0 4 0
参数说明
threshold:浮点对比阈值,默认0.0001,可根据实际数据精度调整,避免浮点计算误差导致的判断错误sort_col:优化版的预排序列,建议选择数值区分度高的列,进一步提升运行效率
内容的提问来源于stack exchange,提问作者bprsch
相关产品推荐
相关产品推荐

