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

如何实现DataFrame行嵌套循环,使内循环从外循环行+1开始?

解决DataFrame嵌套循环:内循环从外循环当前行的下一行开始

你需要对DataFrame的行执行嵌套循环,要求内循环从外循环当前行的下一行(即outer_row + 1)启动,而非默认的从第一行开始。同时在每次内循环中,当外循环行的Home值与内循环行的Home值相等时,计算两者Block值差值的绝对值并存入列表。

示例DataFrame

import pandas as pd

df = pd.DataFrame({
    'Cycle': [100, 130, 200, 300, 350],
    'Home': [1, 1, 2, 1, 3],
    'Block': [400, 500, 200, 300, 100]
})

对应的DataFrame结构:

Cycle  Home  Block
0    100     1    400
1    130     1    500
2    200     2    200
3    300     1    300
4    350     3    100

期望迭代顺序

  • 外循环索引0 → 内循环索引1、2、3、4
  • 外循环索引1 → 内循环索引2、3、4
  • 外循环索引2 → 内循环索引3、4
  • 外循环索引3 → 内循环索引4
  • 外循环索引4 → 无后续内循环

解决方案

方法1:基于索引的循环(高效控制范围)

直接利用DataFrame的索引范围,外循环遍历每个索引,内循环从outer_idx + 1开始到最后一个索引,精准控制迭代顺序:

result = []

for outer_idx in df.index:
    outer_row = df.loc[outer_idx]
    # 内循环仅处理当前索引之后的行
    for inner_idx in df.index[outer_idx + 1:]:
        inner_row = df.loc[inner_idx]
        if outer_row['Home'] == inner_row['Home']:
            diff = abs(outer_row['Block'] - inner_row['Block'])
            result.append(diff)

print(result)
# 输出: [100, 100, 200]

方法2:结合iterrows与索引判断

如果习惯使用iterrows(),可以同时获取索引和行数据,在内循环中跳过索引小于等于外循环索引的行:

result = []

for outer_idx, outer_row in df.iterrows():
    for inner_idx, inner_row in df.iterrows():
        if inner_idx <= outer_idx:
            continue
        if outer_row['Home'] == inner_row['Home']:
            diff = abs(outer_row['Block'] - inner_row['Block'])
            result.append(diff)

print(result)
# 输出: [100, 100, 200]

注意:该方法会遍历所有内循环行再跳过不符合条件的,数据量较大时效率不如方法1。

结果说明

根据示例DataFrame,符合条件的计算逻辑如下:

  • 索引0(Home=1)与索引1(Home=1):abs(400-500)=100
  • 索引0(Home=1)与索引3(Home=1):abs(400-300)=100
  • 索引1(Home=1)与索引3(Home=1):abs(500-300)=200
    最终结果列表为[100, 100, 200]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:25:16