Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reindex a Pandas Dataframe

I have a pandas dataframe in Python.

          datetime           machineID
0   2021-10-01 00:00:00        1.0
1   2021-10-01 00:00:00        2.0
2   2021-10-01 00:00:00        3.0
3   2021-10-01 00:00:00        4.0
4   2021-10-01 00:00:00        5.0
... ... ...
443 2021-10-07 12:00:00       28.0
444 2021-10-07 12:00:00       29.0
445 2021-10-07 12:00:00       30.0
446 2021-10-07 12:00:00       31.0
447 2021-10-07 12:00:00       32.0

There are 7 days in this dataframe from 2021-10-01 to 2021-10-07. This is indexed as per datetime like for every machineID, all the machineIDs come for that date then for next date all machineIDs come and so on.

What I want is, I want to reindex this dataframe such that for each machineID, all 7 dates come then for next machineID all dates come. Something like this,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

          datetime           machineID
0   2021-10-01 00:00:00        1.0
1   2021-10-02 00:00:00        1.0
2   2021-10-03 00:00:00        1.0
3   2021-10-04 00:00:00        1.0
4   2021-10-05 00:00:00        1.0
... ... ...
443 2021-10-03 12:00:00       32.0
444 2021-10-04 12:00:00       32.0
445 2021-10-05 12:00:00       32.0
446 2021-10-06 12:00:00       32.0
447 2021-10-07 12:00:00       32.0

I am not able to find any method to do so.

>Solution :

I think you may be looking for df.sort_values()

df.sort_values(by=['machineID', 'datetime'])

You may need to tinker with the parameter <ascending=True/False> to get your desired result.

Documentation available here:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading