如何根据熊猫中的日期过滤时间?

时间:2021-03-01 06:45:25

标签: python pandas datetime filtering

我在 mysql 中有这些数据,我已经使用 read_sql 将其读入 Pandas。数据:

const array = ["John", "John", "Herald", "John"].map(el => el === 'John' ? 'Margaret' : el);

console.log(array);

我已将列转换为所需的日期时间格式。现在我想在 19:00:00 和 20:00:00 之间找到 28 日的计数。我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以通过 Series.between 中的 boolean indexing 创建日期时间和过滤器:

df['datetime'] = pd.to_datetime(df['Day'] + ' ' + df['InTime'])

df1 = df[df['datetime'].between('2021-02-28 19:00:00', '2021-02-28 20:00:00')]
print (df1)
   count    InTime         Day            datetime
0      1  19:10:14  2021-02-28 2021-02-28 19:10:14
1      2  19:10:26  2021-02-28 2021-02-28 19:10:26
2      3  19:10:47  2021-02-28 2021-02-28 19:10:47
3      4  19:10:47  2021-02-28 2021-02-28 19:10:47

如果只需要过滤 count 列,请使用 DataFrame.loc

s = df.loc[df['datetime'].between('2021-02-28 19:00:00', '2021-02-28 20:00:00'), 'count']
print (s)
0    1
1    2
2    3
3    4
Name: count, dtype: int64