1

I'm using pandas and python. I would like to update the index of my data-frame after sorting. but It is not working at all. Any clues would be most helpful.

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("-----------------")

this gives me the following output:

   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
-----------------

But the index of the first column doesn't change at all. Any help would be appreciated

1 Answer 1

3

You need assign back:

data2 = data2.reset_index(drop=False)

I think inplace is not good practice, check this and this. But if really want it is possible use:

data2.reset_index(drop=False, inplace=True)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.