How to change order of indexes based on my opinion not based on some key in Pandas Data Frame in Python? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to change order of indexes based on my opinion not based on some key in Pandas Data Frame in Python? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have Data Frame in pandas like below:

IDX    col1
------|-------
ABC   | 1
DEF   | 33
GHI   | 18

And column “IDX” is an index of this Data Frame, my question is: How can I change order of indexes in this Data Frame, because for example I would like to have Data Frame like below:

IDX    col1
------|-------
GHI   | 18
ABC   | 1
DEF   | 33

So, I do not want to cahnge the order of indexes based on some key like ascending or something liek this, I need to do it based on my priva opinion, because that’s just the order I wanted 🙂

How can I do that in Python Pandas ?

Answer

Use reindex:

>>> df.reindex(["GHI", "ABC", "DEF"])
     col1
IDX      
GHI    18
ABC     1
DEF    33

Alternatively, use loc:

>>> df.loc[["GHI", "ABC", "DEF"]]
     col1
IDX      
GHI    18
ABC     1
DEF    33
We are here to answer your question about How to change order of indexes based on my opinion not based on some key in Pandas Data Frame in Python? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji