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)
两种方法最终输出的结果都符合目标要求:
| id | pos_X | pos_y | pos_xend | pos_yend |
|---|---|---|---|---|
| 1 | 100 | 0 | 68 | 17 |
| 2 | 42 | 28 | 94 | 35 |
| 3 | 15 | 59 | 84 | 19 |
内容的提问来源于stack exchange,提问作者vt24
相关产品推荐
相关产品推荐

