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

Compare time (hours and minutes) when looping in dataframe

I have the following sample data:

custom_date_parser = lambda x:datetime.strptime(x, "%m/%d/%Y %H:%M") 
df = pd.read_csv('sample.csv', index_col = 0, parse_dates = ['date'], date_parser = custom_date_parser)

|         date          | value   |
| -------------------   | --------|
| 2021-12-06 08:30:00   | 100     |
| 2021-12-06 08:35:00   | 150     |
| 2021-12-06 08:40:00   | 120     |
| 2021-12-06 08:45:00   | 90      |
| 2021-12-06 08:50:00   | 80      |
...................................
| 2021-12-09 08:30:00   | 220     |
| 2021-12-09 08:35:00   | 250     |
| 2021-12-09 08:40:00   | 260     |
| 2021-12-09 08:45:00   | 290     |
| 2021-12-09 08:50:00   | 300     |

I want to loop through the dataframe and print the number in ‘value’ column if the hours and minutes ’08:40:00′ are in the index column. I’ve tried funny stuff like:

for i in df.index:
    if '08:40:00' in [i]:
        print(df.value[i])

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

>Solution :

Since you’ve parsed it into a datetime object, you can check the hour and the minute, filter the dataframe to those rows that match and print the corresponding values.

for x in df.loc[(df['date'].dt.hour.eq(8)) & (df['date'].dt.minute.eq(40))]['value']:
    print(x)
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