Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse DataFrame Column, But Maintain the Index

Tags:

python

pandas

Consider the following

In [214]: df = pd.DataFrame(index=range(4,8), data=[33,22,11,00])

In [215]: df
Out[215]: 
    0
4  33
5  22
6  11
7   0

I'd like to reverse the order of the first column, but maintain the index in its current order, so df will look like

4   0
5  11
6  22
7  33

I can't seem to find the right reset_index, reindex, etc to make this happen.

like image 975
bcf Avatar asked Mar 11 '23 02:03

bcf


1 Answers

use iloc and slice appropriately

df.iloc[::-1]

    0
7   0
6  11
5  22
4  33

In order to preserve the index

use iloc

df.iloc[:] = df.iloc[::-1].values

use numpy

pd.DataFrame(df.values[::-1], df.index, df.columns)

Both yield

    0
4  33
5  22
6  11
7   0
like image 108
piRSquared Avatar answered Mar 23 '23 18:03

piRSquared