Brainiac
Brainiac

Reputation: 159

Sorting Dictionary of Dataframes that have timestamps as values

So I have dictionary created on basis of different types of job that needs to be performed throughout the day.

I need to sort dictionary based on first value of TIME column of all Dataframes so if this pic is example, after sort I get keys in order 1,2,0 based on timestamps. After assigning I delete that slice of that particular dataframe and that I need to sort Dictionary. Here's what my dataframe looks like:

[(0,
                             TIME
  CheckPoints                    
  DSG         2020-11-30 10:00:28
  SHD         2020-11-30 10:06:15
  SLAP        2020-11-30 10:10:16
  KG          2020-11-30 10:16:07
  RI          2020-11-30 10:42:18
  
  [76 rows x 1 columns]),
 (1,
                             TIME
  CheckPoints                    
  DEPOT       2020-11-30 05:12:00
  SLAP        2020-11-30 05:27:00
  SHD         2020-11-30 05:32:45
  DSG         2020-11-30 05:38:55
  DSG         2020-11-30 05:40:00
  
  [102 rows x 1 columns]),
 (2,
                             TIME
  CheckPoints                    
  DEPOT       2020-11-30 05:30:01
  SLAP        2020-11-30 05:45:01
  SHD         2020-11-30 05:49:23
  DSG         2020-11-30 05:55:33
  ATHA        2020-11-30 06:07:39

EDIT:- Throwing in code snippet of dictionary so that it can be copy pasted and used as example..Thanks..!

I'm using sorted(rail.items())but I know that won't be working as expected. Could someone help me out..!

Upvotes: 1

Views: 197

Answers (2)

Brainiac
Brainiac

Reputation: 159

@Mortz Thanks mate... As workaround I tried this and worked as per requirement.. complex but somehow worked..

for dum in d.keys():
        if d[dum].size != 0:
            temp.append(d[dum].iloc[0,0])  
    temp1 = sorted(temp)

And then match first element like:

for item in temp1:
        for x in d.keys():
            if d[x].size != 0:
                if d[x].iloc[0,0]==item:
                    break
                else :
                    continue

I know it's complex but thanks for taking out time..!

Upvotes: 0

Mortz
Mortz

Reputation: 4939

You need to pass a "key" to the sorted function - by key here, we mean a function that returns what needs to be sorted on - in your case what needs to be sorted on is the first item of the dataframe

sorted(d, key=lambda x: d[x].reset_index().loc[0, 'TIME'])   

Upvotes: 2

Related Questions