how to set pandas date as index in python

To set a column as the index in pandas DataFrame, you can use the set_index() method.

Here's an example of how to set the 'Date' column as the index:

main.py
import pandas as pd

# Create a sample DataFrame
data = {'Date': ['2020-01-01', '2020-01-02', '2020-01-03'],
        'Value': [10, 20, 30]}
df = pd.DataFrame(data)

# Set 'Date' column as the index
df = df.set_index('Date')

# Verify the result
print(df)
255 chars
13 lines

Output:

main.py
            Value
Date             
2020-01-01     10
2020-01-02     20
2020-01-03     30
90 chars
6 lines

In this example, we first create a DataFrame with a 'Date' column and a 'Value' column. Then, we use the set_index() method to set the 'Date' column as the index of the DataFrame.

Note: Make sure that your 'Date' column is of a datetime data type in pandas. If it's not, you can convert it using pd.to_datetime() function.

related categories

gistlibby LogSnag