subset pandas df based on date in python

Suppose we have a pandas DataFrame with a column of date values named Date. To subset the DataFrame based on a specific date range, we can use the following code:

main.py
import pandas as pd

# create DataFrame
df = pd.DataFrame({'Date': ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-05'], 
                   'Value': [1, 2, 3, 4, 5]})

# convert 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'])

# subset DataFrame based on date range
start_date = '2020-01-02'
end_date = '2020-01-04'
subset_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]
430 chars
14 lines

In the code above, we first convert the Date column to a datetime format using pd.to_datetime(). Then we define the start and end dates for our subset and use boolean indexing to return only the rows in the date range. The resulting subset DataFrame is stored in subset_df.

related categories

gistlibby LogSnag