Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select rows in a data frame based on the date range

I have a list of dictionaries:

mylist=
[{'Date': '10/2/2021', 'ID': 11773, 'Receiver': 'Mike'},
{'Date': '10/2/2021', 'ID': 15673, 'Receiver': 'Jane'},
{'Date': '10/3/2021', 'ID': 11773, 'Receiver': 'Mike'},
... 
{'Date': '12/25/2021', 'ID': 34653, 'Receiver': 'Jack'}]

I want to select the rows within a date range, for example from 10/3/2021 to 11/3/2021. I tried the following steps:

dfmylist = pd.DataFrame(mylist)
dfmylistnew = (dfmylist['Date'] > '10/3/2021') & (dfmylist['Date'] <= '11/3/2021')

I converted my list to a data frame and then select the date range. However, the dfmylistnew data frame doesn’t show up properly. What did I miss?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The output of dfmylistnew is:

0    False
1    False
2    False
3    False
4    False
Name: Date, dtype: bool

>Solution :

You missed to convert the "Date" to datetime type:

import pandas as pd

mylist=[{'Date': '10/2/2021', 'ID': 11773, 'Receiver': 'Mike'},
{'Date': '10/2/2021', 'ID': 15673, 'Receiver': 'Jane'},
{'Date': '10/3/2021', 'ID': 11773, 'Receiver': 'Mike'},
{'Date': '12/25/2021', 'ID': 34653, 'Receiver': 'Jack'}]

dfmylist = pd.DataFrame(mylist)

dfmylist['Date'] = pd.to_datetime(dfmylist['Date']) # you missed this line

dfmylistnew = (dfmylist['Date'] > '10/2/2021') & (dfmylist['Date'] <= '11/3/2021')

dfmylist.loc[dfmylistnew]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading