0

I have a dataframe df with the next attributes (one of them is a Datetime attribute as a String):

+-------------+---------+-------+
| Date        |  Atr1   |  Atr2 |
+-------------+---------+-------+
| '1/1/2015'  |  'A'    |   'B' |
+-------------+---------+-------+
| '1/1/2015'  |  'B'    |   'H' |
+-------------+---------+-------+
| '1/3/2015'  |  'C'    |   'J' |
+-------------+---------+-------+
| '2/3/2015'  |  'D'    |   'L' |
+-------------+---------+-------+

I have the dataframe sorted by the Date object, but then, I groupbed by the datetime and generate one dataframe per group like this:

dates = df.groupby('Date')

dict_fechas_df = {}

for f in fechas:
    fecha = f[0]
    dict_fechas_df[fecha] = fecha

But when checking the keys of the dictionary, the dates appear disordered. How can I then get the dictionary ordered?

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
jartymcfly
  • 1,945
  • 9
  • 30
  • 51

1 Answers1

1

Add parameter sort=False to groupby:

dates = df.groupby('Date', sort=False)

Alternative solution for dictionaries:

dict_fechas_df = dict(tuple(dates))

But if want order of keys in dictionaries, need python 3.6+, bellow OrderDict, check this.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252