sort by date when data is set t oindex in python

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.py
import pandas as pd

# create example dataframe with dates as index
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
}, index=pd.to_datetime(['2021-01-01', '2021-01-03', '2021-01-02']))

# sort dataframe by date
df = df.sort_index(key=lambda x: x)

print(df)
269 chars
13 lines

Output:

main.py
            A  B
2021-01-01  1  4
2021-01-02  3  6
2021-01-03  2  5
68 chars
5 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.

related categories

gistlibby LogSnag