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

如何在Pandas中选取含Scope_list的行及其后续3行?

解决方案

步骤思路

要实现需求,核心是先定位所有Scope_list行的索引,再把每个索引及其后3个索引(共4个)收集起来,最后用这些索引筛选数据即可。需要注意处理索引超出数据长度的情况,以及可能的重复索引(比如两个目标行间隔小于4行时)。

完整代码

import pandas as pd

# 你的原始数据
df = pd.DataFrame(['Scope_list', 'Light_front', 'Box1', 'Cable1', 'Connector', 'Switch', 'Info_list', 'can be used for 1', '456 not used','','Scope_list', 'Light_front', 'Cable1', 'Connector', 'Code_list', '345,456,567', '567', '', 'Scope_list', 'Light_left', 'Box2', 'Cable3', 'Switch3'], columns = ['parts'])

# 1. 获取所有Scope_list行的索引
scope_indices = df[df['parts'] == 'Scope_list'].index

# 2. 生成需要保留的索引:每个目标索引 + 后续3个索引(共4个)
keep_indices = []
for idx in scope_indices:
    # 添加当前索引和之后3个,同时确保不超过DataFrame的最大索引
    for offset in range(4):
        current_idx = idx + offset
        if current_idx < len(df):
            keep_indices.append(current_idx)

# 3. 去重并排序(避免重复索引,保证顺序正确)
keep_indices = sorted(list(set(keep_indices)))

# 4. 筛选数据
result = df.loc[keep_indices]
print(result)

代码解释

  • 步骤1:通过布尔索引定位所有parts列值为Scope_list的行,提取它们的索引。
  • 步骤2:遍历每个目标索引,依次添加当前索引和后3个索引,同时判断索引是否超出数据总长度,防止越界错误。
  • 步骤3:将收集到的索引去重(比如两个目标行间隔过近时会出现重复索引),再排序保证顺序和原数据一致。
  • 步骤4:用整理好的索引筛选原DataFrame,得到最终需要的结果。

运行结果

针对你的测试数据,运行后会得到:

parts
0    Scope_list
1   Light_front
2          Box1
3        Cable1
10   Scope_list
11  Light_front
12        Cable1
13     Connector
18   Scope_list
19   Light_left
20         Box2
21       Cable3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:35:27