如何从数据帧中查找属于时间范围内的行?

问题描述 投票:0回答:1

我想从我的数据框中找到上午 7 点到上午 11 点(含)之间的所有行

使用此代码,我将 csv 读入包含相关数据的数据框中

df = pd.read_csv(info.csv)
amount_df = pd.DataFrame(df['amount'])
datetime_df = pd.DataFrame((pd.to_datetime(df['datetime'])).dt.time)
concat_df = pd.concat([datetime_df, amount_df], axis=1)

数据框如下所示:

日期时间 金额
00:51:00 15.84
00:35:00 11.64
00:13:00 10.20
00:33:00 8.00
00:53:00 22.95

当我运行以下代码时,它会给出正确的时间,但不会包含时间 = 11:00:00 时的实例

mask = (df['datetime'].dt.hour <= 6) & (df['datetime'].dt.hour >= 11)
concat_df = concat_df[~mask]

我尝试使用 .loc 但它不会准确返回 11:00:00 的任何实例

pandas dataframe datetime pandas-loc
1个回答
0
投票

您可以创建一个另外专门要求 11:00:00 的掩码。因此,要查找上午 7 点到上午 11 点之间的所有时间,您可以使用:

mask = ((df.index.hour >= 7) & (df.index.hour <= 10)) | ((df.index.hour == 11) & (df.index.minute == 0) & (df.index.second == 0))
df1 = df[mask]

这给了我:

                         time
2024-01-01 07:00:00  07:00:00
2024-01-01 07:00:01  07:00:01
2024-01-01 07:00:02  07:00:02
                         time
2024-01-01 10:59:58  10:59:58
2024-01-01 10:59:59  10:59:59
2024-01-01 11:00:00  11:00:00
© www.soinside.com 2019 - 2024. All rights reserved.