pandas排序并保持索引不变
pandas sort and keep index unchanged
我想按列对数据框进行排序,但我遇到了问题
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 保留在升序。
我想你需要 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
我想按列对数据框进行排序,但我遇到了问题
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 保留在升序。
我想你需要 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