pandas排序并保持索引不变

时间:2016-10-05 12:32:36

标签: sorting pandas indexing series

我想按列对数据进行排序,而我遇到了问题

df = pd.DataFrame(np.random.random(5))
df.sort(columns = [0],inplace = True)
df

           0
4   0.275867
1   0.304362
2   0.625837
0   0.741176
3   0.767829

当我对列进行排序时,我得到了我没想到的结果,我预计索引应该仍然是0,1,2,3,4,那么我怎样才能获得该结果并保持列0在升序中顺序。

1 个答案:

答案 0 :(得分:4)

我认为您需要reset_index参数drop=True

np.random.seed(1)
df = pd.DataFrame(np.random.random(5))
df.sort_values(by=[0],inplace = True)
print (df)
          0
2  0.000114
4  0.146756
3  0.302333
0  0.417022
1  0.720324

df.reset_index(drop=True, inplace=True)
print (df)
          0
0  0.000114
1  0.146756
2  0.302333
3  0.417022
4  0.720324