how to set date as index in pandas in python

Assuming that you have a column in your DataFrame that contains the date values, you can set it as the index using the set_index method and passing the name of the date column as argument. Here's an example:

main.py
import pandas as pd
from datetime import datetime

# create a DataFrame with dates as a column
data = {'date': [datetime(2021, 1, 1), datetime(2021, 1, 2), datetime(2021, 1, 3)],
        'value': [10, 20, 30]}
df = pd.DataFrame(data)

# set the date column as the index
df.set_index('date', inplace=True)

print(df)
316 chars
13 lines

This will output:

main.py
            value
date             
2021-01-01     10
2021-01-02     20
2021-01-03     30
90 chars
6 lines

Note that the inplace=True argument modifies the DataFrame in place, so there is no need to assign the result to a new variable.

related categories

gistlibby LogSnag