bcf
bcf

Reputation: 2134

Reverse DataFrame Column, But Maintain the Index

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.

Upvotes: 4

Views: 3563

Answers (2)

NinjaGaiden
NinjaGaiden

Reputation: 3146

You can also set your index into a temporary variable and then reapply index.

idx = df.index.values
df.sort_values([0], inplace=True)
df.index = idx

Not as clever but easy to understand

Upvotes: 0

piRSquared
piRSquared

Reputation: 294258

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

Upvotes: 9

Related Questions