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

Python pandas如何从DataFrame同一列提取连续索引对应的两个值

问题原因及解决方法

原代码报错原因

原代码中row['first_column']是当前行对应列的单个标量值,不是Series结构,调用.values(index + 1)属于语法错误,因此会触发报错。

可行实现方案

方案1:调整循环逻辑(保留循环写法)

遍历的时候注意不要越界到最后一行之后,两种写法可选:

写法A:直接按索引遍历

import pandas as pd
data = {'first_column':  [1, 2, 3, 4, 5],
        'second_column': [1, 2, 3, 4, 5],
        }
df = pd.DataFrame(data)

# 遍历到倒数第二行即可
for i in range(len(df) - 1):
    current_val = df['first_column'].iloc[i]
    next_val = df['first_column'].iloc[i+1]
    # 可在此处对成对值做后续处理
    print((current_val, next_val))

写法B:保留iterrows使用习惯

n_rows = len(df)
for index, row in df.iterrows():
    # 跳过最后一行,避免越界
    if index == n_rows - 1:
        break
    current_val = row['first_column']
    next_val = df['first_column'].iloc[index + 1]
    # 可在此处对成对值做后续处理
    print((current_val, next_val))

方案2:向量化写法(无需循环,性能更优,推荐)

用pandas内置的shift方法直接生成偏移列,批量生成配对结果,数据量越大性能优势越明显:

# 生成偏移后的配对列,删除最后一行空值
pair_df = pd.DataFrame({
    'current': df['first_column'],
    'next_val': df['first_column'].shift(-1)
}).dropna()

# 转成元组列表可直接使用
pair_list = list(pair_df.itertuples(index=False, name=None))
print(pair_list) 
# 输出:[(1, 2), (2, 3), (3, 4), (4, 5)]

关于iteritems()的疑问

iteritems()(pandas新版本已更名为items())是遍历列的迭代器,返回的是(列名, 列Series)的成对结果,你的需求是按行取相邻数值,用iteritems()反而会增加逻辑复杂度,没有直接遍历索引或者用iterrows方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:06:04