im trying to rotate the rows of a dataframe, where the firt rows is the last row, the second the first and so on
Original
A | |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |
5 | 6 |
Result
A | |
---|---|
0 | 6 |
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
5 | 5 |
How i can do this?
CodePudding user response:
Use np.roll
from numpy:
import numpy as np
df['A'] = np.roll(df['A'], 1)
print(df)
# Output:
A
0 6
1 1
2 2
3 3
4 4
5 5
CodePudding user response:
I think you might need to use np.arange()
with iloc[]
. If you want the index to remain unaltered add .reset_index()
:
df = pd.DataFrame({'A':[1,2,3,4,5,6]})
df.iloc[np.arange(-1, len(df)-1)].reset_index(drop=True)
Returns:
A
0 6
1 1
2 2
3 3
4 4
5 5
CodePudding user response:
If you're looking for a solution with pandas only, this should do the job for you-
df = pd.concat([df.iloc[-1:], df.iloc[0:-1]])
df.reset_index(inplace=True, drop=True)