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])
CodePudding user response:
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)
CodePudding user response:
From your dataset, as the date
column is in the Datetime format, we can simply filter on the desired time like so :
>>> df[df['date'].dt.strftime("%H:%M:%S") == '08:40:00']
date value
2 2021-12-06 08:40:00 120
7 2021-12-09 08:40:00 260
CodePudding user response:
I would set your date field as the DateTimeIndex.
You could then use something like this to filter the minute and hour.
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
df[df.index.minute == 40] & df[df.index.hour == 8]