Hi.
I think the problem is caused by the groups not being in your desired order, prior to writing to the Excel workbook.
So the first step is to ensure your groups are in the desired order. Sorting your groups in descending order of your datetime field should work if you pre-sort the rows by Field Name
with ascending=False
, before the groupby, AND you specify sort=False
in the groupby.
Here’s an example below, and I’m using a datetime column named Field
as the groupby key, with values created out of order.
In [1]: from datetime import timedelta; import pandas as pd
In [2]: df = pd.DataFrame().assign(
...: Field=[now - timedelta(days=2), now, now - timedelta(days=1)],
...: SomeOtherField=[2, 0, 1]
...: )
In [3]: df
Out[3]:
Field SomeOtherField
0 2024-02-06 23:02:46.253608 2
1 2024-02-08 23:02:46.253608 0
2 2024-02-07 23:02:46.253608 1
Note: The Field
column is created from datetime
objects so it will end up as datetime64[ns]
.
Now I pre-sort the rows by Field
with ascending=False
, chained with the groupby on Field
with sort=False
:
In [4]: for key, _ in df.sort_values('Field', ascending=False).groupby('Field', sort=False):
...: print(key)
...:
2024-02-08 23:02:46.253608
2024-02-07 23:02:46.253608
2024-02-06 23:02:46.253608
The documentation on Pandas groupby key sorting suggests that the default option of sort=True
uses ascending ordering, so sort=False
would reverse that.
Without the pre-sorting step the groupby with sort=False
does not work.
In [5]: df = pd.DataFrame().assign(
...: Field=[now - timedelta(days=2), now, now - timedelta(days=1)],
...: SomeOtherField=[2, 0, 1]
...: )
In [6]: for key, _ in df.groupby('Field', sort=False):
...: print(key)
...:
2024-02-06 23:02:46.253608
2024-02-08 23:02:46.253608
2024-02-07 23:02:46.253608
I’ve tested the steps to write the Excel workbook, and it seems to work.
In [7]: with pd.ExcelWriter('test.xlsx') as writer:
...: for key, g in df.sort_values('Field', ascending=False).groupby('Field', sort=False):
...: g.to_excel(writer, sheet_name=str(key.strftime("%Y-%m-%d")), index=False, header=True)
...:
I don’t have Excel installed, but if I open this test.xlsx
file with a free online Excel editor I can see the sheets ordered in descending order of date.