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

如何基于Pandas DataFrame位置选取指定范围元素并合并

提取目标位置前后范围的数据列表

原始数据定义

import pandas as pd

diff = [10,15,20,25,20,15, 10, 10, 15, 21, 24, 19, 15, 10, 10, 15, 20, 21, 26, 20, 10,15, 20, 25, 20, 15, 10]
df_data = pd.DataFrame(diff, columns=['data']) 
df_data.insert(0, 'slno', [d for d in range(0, df_data.shape[0])])

max_dict = {
    'pos':[3,10,18,23],
    'val' :[25, 24, 26, 25]
}
df_max = pd.DataFrame(max_dict)

实现方法

通过apply函数遍历df_max中的每个pos值,提取df_data中对应位置前2个、当前、后2个的data值组成列表,最终添加为新列range:

def get_surrounding_data(pos):
    # 计算起始和结束索引,避免越界
    start_idx = max(0, pos - 2)
    end_idx = min(df_data.index[-1], pos + 2)
    # 提取对应范围的data值并转为列表
    return df_data.loc[start_idx:end_idx, 'data'].tolist()

# 生成新列range
df_max['range'] = df_max['pos'].apply(get_surrounding_data)

验证结果

执行后df_max的结果如下:

posvalrange
325[15, 20, 25, 20, 15]
1024[10, 15, 21, 24, 19]
1826[21, 26, 20, 10, 15]
2325[15, 20, 25, 20, 15]

说明

  • 函数get_surrounding_data中通过max(0, pos-2)和min(df_data.index[-1], pos+2)处理了边界情况,避免索引越界(比如当pos为0、1或最后两个位置时)
  • 使用df_data.loc[start_idx:end_idx, 'data'].tolist()直接提取指定范围的数值并转为列表

内容的提问来源于stack exchange,提问作者S N B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:40:13