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

如何基于列数值增量筛选DataFrame:按指定差值选取行

基于数值列增量筛选DataFrame行的实现方法

你需要的是基于指定列的数值增量(而非时间维度)筛选行,要求每次选中行的数值与上一个选中值的差值达到设定阈值(比如10),asfreq、resample这类时间相关方法无法满足需求,下面给出两种适配不同场景的实现方案:

场景1:按数值从小到大筛选(忽略原始行顺序)

如果你的数据不需要保留原始行顺序,希望按数值递增的逻辑筛选,可使用以下代码:

示例代码

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'Column A': ['12:05', '13:05', '14:05', '15:05'],
    'Column B': [1, 6, 11, 16]
})

def filter_by_value_increment(df, value_col, threshold):
    # 先按目标数值列排序,确保筛选逻辑按数值递增执行
    sorted_df = df.sort_values(value_col).reset_index(drop=True)
    selected_indices = [0]  # 默认选中第一个值
    last_selected_val = sorted_df[value_col].iloc[0]
    
    # 遍历后续行,判断差值是否达标
    for idx, current_val in enumerate(sorted_df[value_col][1:]):
        if current_val - last_selected_val >= threshold:
            selected_indices.append(idx + 1)
            last_selected_val = current_val
    return sorted_df.iloc[selected_indices]

# 调用函数,阈值设为10
filtered_df = filter_by_value_increment(df, 'Column B', 10)
print(filtered_df)

输出结果

Column A  Column B
0    12:05         1
2    14:05        11

场景2:保留原始行顺序筛选

如果需要保留数据的原始行顺序,仅在顺序遍历中筛选符合增量要求的行,可使用以下调整后的函数:

示例代码

def filter_by_value_increment_keep_order(df, value_col, threshold):
    selected_indices = [0]
    last_selected_val = df[value_col].iloc[0]
    
    # 按原始顺序遍历每一行
    for idx in range(1, len(df)):
        current_val = df[value_col].iloc[idx]
        if current_val - last_selected_val >= threshold:
            selected_indices.append(idx)
            last_selected_val = current_val
    return df.iloc[selected_indices]

# 测试扩展数据(包含后续值12、15、17、21)
df_extended = pd.DataFrame({
    'Column A': ['12:05', '13:05', '14:05', '15:05', '16:05', '17:05', '18:05', '19:05'],
    'Column B': [1, 6, 11, 16, 12, 15, 17, 21]
})

filtered_extended = filter_by_value_increment_keep_order(df_extended, 'Column B', 10)
print(filtered_extended)

输出结果

Column A  Column B
0    12:05         1
2    14:05        11
7    19:05        21

关键说明

  • 两个方案的核心逻辑都是跟踪上一个选中的数值,遍历判断当前值与它的差值是否达到阈值;
  • 如果你的数据中存在重复值或非递增的数值,可根据实际需求选择是否提前去重或排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:30:33