如何实现DataFrame行旋转,将最后一行移至首行其余行依次后移
Pandas DataFrame行旋转操作实现方案
需求说明
将DataFrame最后一行移至首行,其余行依次后移一位,保持原始索引不变。你给出的示例中,原A列值为[1,2,3,4,5,6],处理后预期得到[6,1,2,3,4,5]。
实现方法
方法1:numpy滚动函数(最简实现)
直接对DataFrame的值做轴向滚动,操作效率最高,默认保持原有索引不变:
import pandas as pd import numpy as np # 构造示例数据 df = pd.DataFrame({'A': [1,2,3,4,5,6]}, index=range(6)) # 对A列执行滚动偏移1位 df['A'] = np.roll(df['A'], shift=1) # 若需要对全表所有列执行相同操作,替换为: # df.iloc[:,:] = np.roll(df, shift=1, axis=0)
方法2:DataFrame拼接(逻辑直观)
通过拆分和拼接行实现,更易理解执行逻辑:
# 拆分最后一行和剩余行 last_row = df.tail(1) prev_rows = df.head(len(df)-1) # 拼接后重置索引,保持原始0~n的索引顺序 df = pd.concat([last_row, prev_rows], ignore_index=True)
效果验证
两种方法处理后,输出df可得到符合要求的结果:
| 索引 | A |
|---|---|
| 0 | 6 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
内容的提问来源于stack exchange,提问作者Alexis Olivero Aimaretti
相关产品推荐
相关产品推荐

