0

Hey guys have tried finding a solution to filtering data by month and year but havent found appropriate answer. Here is how my dataset looks like:

import pandas as pd
df = pd.DataFrame([('Jorh Hospital','2017-03-15', 389.0,34, 32, 34),
                   ('orh Hospital','2018-04-20', np.nan,22, 5, 43),
                   ('Jorh Hospital','2018-05-20', np.nan,22, 5, 43),
                   ('Bugh Hospital','2019-02-16', 80.5,np.nan, 56, np.nan),
                   ('Bugeh Hospital','2019-03-23', np.nan,89, 67, np.nan),
                  ('ugh Hospital','2019-04-23', np.nan,89, 67, np.nan)],
                  columns=('Hosp_name','date', 'max_rec', 'reg_pp', 'disch_no', 'temp_rec'))
df

Using data column, I want to select data from April 2018 to March 2019. Kindly assist me with simple way to use month and date range to filter this data. Here is what I tried

df['date'] = pd.to_datetime(df['date'], errors='coerce')
df['date'] = df['date'].dt.to_period('m')
df[(df['date'] > '2018-04') & (df['date'] <= '2019-03')]

This ain't working as expected, its giving me two table outputs. what am I missing

LivingstoneM
  • 1,088
  • 10
  • 28
  • 1
    Try `df[df.date.between('2018-04', '2019-03')]` ? (after `df['date'] = pd.to_datetime(df['date'], errors='coerce')`) – Chris Adams Mar 10 '20 at 20:36
  • Does this answer your question? [Select DataFrame rows between two dates](https://stackoverflow.com/questions/29370057/select-dataframe-rows-between-two-dates) – AMC Mar 10 '20 at 21:45

0 Answers0