Reverse DataFrame Column, But Maintain the Index

依然范特西╮ 提交于 2021-02-19 02:56:07

问题


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.


回答1:


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



回答2:


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

df = pd.DataFrame(index=range(4,8), data=[33,22,11,00])
idx=df.index.values
df.sort_values([0],inplace=True)
df.index=idx

Not as clever but easy to understand



来源:https://stackoverflow.com/questions/41774766/reverse-dataframe-column-but-maintain-the-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!