how to set pandas date as index in python and drop the date column in python

To set a date column as the index in pandas and drop the date column, you can follow the steps below:

main.py
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'date': ['2021-01-01', '2021-01-02', '2021-01-03'],
                   'value': [10, 20, 30]})
print("Before setting date as index:")
print(df)

# Convert 'date' column to datetime
df['date'] = pd.to_datetime(df['date'])

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

# Drop the 'date' column
df.drop('date', axis=1, inplace=True)

print("\nAfter setting date as index and dropping the 'date' column:")
print(df)
500 chars
20 lines

Output:

main.py
Before setting date as index:
         date  value
0  2021-01-01     10
1  2021-01-02     20
2  2021-01-03     30

After setting date as index and dropping the 'date' column:
            value
date             
2021-01-01     10
2021-01-02     20
2021-01-03     30
265 chars
13 lines

In the code above, we first convert the 'date' column to datetime using pd.to_datetime(). Then, we set the 'date' column as the index of the DataFrame using set_index(). Finally, we drop the 'date' column using drop() with axis=1 to specify the column axis.

gistlibby LogSnag