Filter dataset for current month only

Viewed 154

I have a dataset with a column which contains dates (e.g. 09/17/20) as object. I want to filter all my rows based on the current month.

import pandas as pd
import datetime as  dt
from datetime import datetime    
df =  pd.read_csv("dataset.csv", dtype="unicode") 
now = datetime.now()
df['month_start'] = pd.to_datetime(df['month_start'], format = "%Y-%d-%m")
mask = df['month_start'].dt.strftime("%Y-%m") == datetime.today().strftime("%Y-%m")
include = df[mask]
df.to_csv("dates.csv")
print(datetime.today().strftime("%Y-%m"))

My attempt doesn't filter the dates at all as I want rows with the current month only.

1 Answers

Please check the snippet.

I fetched all months from dataframe and stored it in a list and fetched all years and stored in another list which then i compared with current month and current year and then I accessed common values from both list and finally using index value I used iloc to locate the given rows

import pandas as pd
from datetime import datetime
df =  pd.read_csv("data.csv", dtype="unicode") 
amon = pd.DatetimeIndex(df['month_start']).month.tolist()
ayear= pd.DatetimeIndex(df['month_start']).year.tolist()
bmon=[i for i,x in enumerate(amon) if((x==datetime.now().month))]
byear=[i for i,x in enumerate(ayear) if((x==datetime.now().year))]
common = [i for i in bmon if i in byear]
df=df.iloc[common]
Input
   month_start
0   08/17/2015
1   09/17/2015
2   09/17/2020
3   07/17/2020
4   06/17/2020

Output
  month_start
2    09/17/2020
Related