Rotate rows of a dataframe

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?

Upvotes: 2

Views: 982

Answers (3)

iamakhilverma
iamakhilverma

Reputation: 596

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)

Upvotes: 0

Corralien
Corralien

Reputation: 120479

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

Upvotes: 3

Celius Stingher
Celius Stingher

Reputation: 18377

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

Upvotes: 1

Related Questions