首页 > 解决方案 > 排序后更新 Pandas 索引

问题描述

我正在使用熊猫和python。我想在排序后更新我的数据框的索引。但它根本不起作用。任何线索都是最有帮助的。

import pandas as pd

data = pd.DataFrame({'Odd':[1,3,5,6,7,9], 'Even':[0,2,42,6,8,10]})
data["colors"]=["red","orange","yellow","green","blue","indigo"]
data["oldindex"]=[0,1,2,3,4,5]
print(data.head(10))
data2 = (data.sort_values(by=["Even"], ascending = False))
data2.reset_index(drop=False)
print("-----------------")
print(data2.head(10))
print("-----------------")

这给了我以下输出:

   Odd  Even  colors  oldindex
0    1     0     red         0
1    3     2  orange         1
2    5    42  yellow         2
3    6     6   green         3
4    7     8    blue         4
5    9    10  indigo         5
-----------------
   Odd  Even  colors  oldindex
2    5    42  yellow         2
5    9    10  indigo         5
4    7     8    blue         4
3    6     6   green         3
1    3     2  orange         1
0    1     0     red         0
-----------------

但是第一列的索引根本没有改变。任何帮助,将不胜感激

标签: pythonpandas

解决方案


您需要重新分配:

data2 = data2.reset_index(drop=False)

我认为inplace这不是一个好习惯,请检查thisthis。但如果真的想要,可以使用:

data2.reset_index(drop=False, inplace=True)

推荐阅读