Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas sort and keep index unchanged

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.

like image 954
Stellera Avatar asked Jan 05 '23 06:01

Stellera


1 Answers

I think you need reset_index with parameter 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
like image 193
jezrael Avatar answered Jan 07 '23 19:01

jezrael