To sort a pandas dataframe by date when the dates are set as the index, you can use the sort_index
method and pass the datetime
index to the key
parameter. Here's an example:
main.py269 chars13 lines
Output:
main.py68 chars5 lines
Note that passing the key
parameter is necessary when sorting by the datetime
index since the index is not a column in the dataframe. In this case, the lambda
function simply returns the index value for each row, allowing sort_index
to use the datetime values for sorting.
gistlibby LogSnag