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

Python中如何为DataFrame创建值来自下一行的新列并整理数据?

解决方案

可以用Pandas的索引筛选或分组功能实现需求,以下是两种可行方法:

方法一:索引筛选拼接

先提取起始行和结束行,再按列合并并调整列名:

import pandas as pd

# 创建原始DataFrame
df = pd.DataFrame({
    'id': [1,2,3,4,5,6],
    'pos_X': [100,68,42,94,15,84],
    'pos_y': [0,17,28,35,59,19]
})

# 提取每一组的起始行(偶数索引:0、2、4)
start_df = df.iloc[::2].reset_index(drop=True)
# 提取每一组的结束行(奇数索引:1、3、5),并重命名列
end_df = df.iloc[1::2][['pos_X', 'pos_y']].rename(columns={'pos_X':'pos_xend', 'pos_y':'pos_yend'}).reset_index(drop=True)

# 合并两部分数据
result = pd.concat([start_df, end_df], axis=1)
# 重置id列
result['id'] = range(1, len(result)+1)

print(result)

方法二:分组处理

通过索引整除实现每两行一组,再从每组中提取对应值:

import pandas as pd

# 创建原始DataFrame
df = pd.DataFrame({
    'id': [1,2,3,4,5,6],
    'pos_X': [100,68,42,94,15,84],
    'pos_y': [0,17,28,35,59,19]
})

# 按每两行分组(索引//2得到分组标识:0、0、1、1、2、2)
result = df.groupby(df.index // 2).apply(
    lambda group: pd.Series({
        'id': group.name + 1,
        'pos_X': group.iloc[0]['pos_X'],
        'pos_y': group.iloc[0]['pos_y'],
        'pos_xend': group.iloc[1]['pos_X'],
        'pos_yend': group.iloc[1]['pos_y']
    })
).reset_index(drop=True)

print(result)

两种方法最终输出的结果都符合目标要求:

idpos_Xpos_ypos_xendpos_yend
110006817
242289435
315598419

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:35:42