pandas 熊猫排序并保持索引不变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39874065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:08:36  来源:igfitidea点击:

pandas sort and keep index unchanged

sortingpandasindexingseries

提问by Stellera

I want to sort a dataframe by column, while I got a problem

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

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

When I sort column, I got the result which I was not expected, I expected the index should still be 0,1,2,3,4, So how can I get that result and keep the column 0 in the ascending order.

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

回答by jezrael

I think you need reset_indexwith parameter drop=True:

我认为你需要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