Python – Pandas: Move rows (indexes and values) from last to first

Pandas: Move rows (indexes and values) from last to first… here is a solution to the problem.

Pandas: Move rows (indexes and values) from last to first

I want to move the entire row (index and value) from the last row to the first row of the DataFrame. Every other example I could find used ordered row index (specifically – My row index is not a sequence of numbers – so I can’t simply add -1 and reindex with +1) or moves the values while maintaining the original index.

I want

to add a row and then I want to move it to row 1. Here is the setting:

df = pd. DataFrame({
    'col1' : ['A', 'A', 'B', 'F', 'D', 'C'],
    'col2' : [2, 1, 9, 8, 7, 4],
    'col3': [0, 1, 9, 4, 2, 3],
}).set_index('col1')

#output
In [7]: df
Out[7]: 
      col2  col3
col1            
A        2     0
A        1     1
B        9     9
F        8     4
D        7     2
C        4     3

Then I add a new line as follows:

df.loc["Deferred Description"] = pd. Series([''])

In [9]: df
Out[9]: 
                      col2  col3
col1                            
A                      2.0   0.0
A                      1.0   1.0
B                      9.0   9.0
F                      8.0   4.0
D                      7.0   2.0
C                      4.0   3.0
Deferred Description   NaN   NaN

I want the result output to be:

In [9]: df
Out[9]: 
                      col2  col3
col1                            
Defenses Description   NaN   NaN
A                      2.0   0.0
A                      1.0   1.0
B                      9.0   9.0
F                      8.0   4.0
D                      7.0   2.0
C                      4.0   3.0

I’ve tried using df.shift() but only the value changes. I’ve also tried df.sort_index() but this requires sorting the index (there are several SO examples using df.loc[-1] = ...). Then reindex with df.index = df.index + 1). In my case, I need to have Defenses Description as the first line.

Related Problems and Solutions