jartymcfly
jartymcfly

Reputation: 2005

How can I groupby in pandas python but conserving the order of the dataframe?

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?

Upvotes: 0

Views: 42

Answers (1)

jezrael
jezrael

Reputation: 862511

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.

Upvotes: 1

Related Questions