WORKING WITH DATE RANGES IN PANDAS
Listing B.13 shows the content of pand_parse_dates.py that shows how to work with date ranges in a CSV file.
Listing B.13: pand_parse_dates.py
import pandas as pd
df = pd.read_csv('multiple_dates.csv', parse_
dates=['dates'])
print("df:")
print(df)
print()
df = df.set_index(['dates'])
start_d = "2021-04-30"
end_d = "2021-08-31"
print("DATES BETWEEN",start_d,"AND",end_d,":")
print(df.loc[start_d:end_d])
print()
print("DATES BEFORE",start_d,":")
print(df.loc[df.index < start_d])
years = ['2020','2021','2022']
for year in years:
year_sum = df.loc[year].sum()[0]
print("SUM OF VALUES FOR YEAR",year,":",year_sum)
Listing B.13 starts by initializing the variable df with the contents of the CSV file multiple_dates.csv and then displaying its contents. The next code snippet sets the dates...