如何获取特定时间段内 Pandas 系列的值?

pandasserver side programmingprogramming更新于 2025/5/18 5:37:17

Pandas Series.between_time() 方法用于选择一天中特定时间段内的值。 between_time() 方法接受两个时间参数并返回具有选定值的系列对象。

between_time 方法类似于 pandas 系列对象的 at_time 方法,at_time 方法选择特定时间的值,而 between_time 方法将选择时间之间的值。

如果输入系列对象的索引不是 DatetimeIndex,它将引发 TypeError。

默认情况下,两个输入时间(start_time、end_time)参数都是包含的,如果您想更改这一点,我们可以使用 include_start 和 include_end 参数。

示例 1

import pandas as pd

# 创建索引
index = pd.date_range('2021-01-1', periods=10, freq='20T')

#使用日期时间索引创建 pandas Series
series = pd.Series([1,2,3,4,5,6,7,8,9,10], index=index)

print(series)

#通过 between_time() 选择值
print("Selecting values:", series.between_time("00:10","1:40"))

解释

在这里,我们使用 pandas DateTime 索引和一些整数值列表创建了一个 pandas.Series 对象。之后,我们应用 between_time() 方法获取时间"00:10"之间的值到"1:40"。

如果指定的时间存在于给定系列对象的索引中,则它将返回一个包含这些 DateTime 索引的收集值的新系列对象。

输出

2021-01-01 00:00:00  1
2021-01-01 00:20:00  2
2021-01-01 00:40:00  3
2021-01-01 01:00:00  4
2021-01-01 01:20:00  5
2021-01-01 01:40:00  6
2021-01-01 02:00:00  7
2021-01-01 02:20:00  8
2021-01-01 02:40:00  9
2021-01-01 03:00:00 10
Freq: 20T, dtype: int64

Selecting values:
2021-01-01 00:20:00 2
2021-01-01 00:40:00 3
2021-01-01 01:00:00 4
2021-01-01 01:20:00 5
2021-01-01 01:40:00 6
Freq: 20T, dtype: int64

我们收集了“00:10”到“1:40”时间之间的值。在此示例中,start_time("00:10")和end_time("1:40")均包含在内。

示例 2

import pandas as pd

# 创建索引
index = pd.date_range('2021-01-1', periods=10, freq='20T')

# 创建带有日期时间索引的 pandas Series
series = pd.Series([1,2,3,4,5,6,7,8,9,10], index=index)

print(series)

# 通过 between_time() 选择值
print("Selecting values:", series.between_time("00:40","1:40", include_start=False,include_end=False))

解释

在下面的示例中,我们通过为 include_start 和 include_end 参数提供 False 值来应用 between_time() 方法,但不包含开始和结束时间。

输出

2021-01-01 00:00:00  1
2021-01-01 00:20:00  2
2021-01-01 00:40:00  3
2021-01-01 01:00:00  4
2021-01-01 01:20:00  5
2021-01-01 01:40:00  6
2021-01-01 02:00:00  7
2021-01-01 02:20:00  8
2021-01-01 02:40:00  9
2021-01-01 03:00:00 10
Freq: 20T, dtype: int64

Selecting values:
2021-01-01 01:00:00 4
2021-01-01 01:20:00 5
Freq: 20T, dtype: int64

在此示例中,我们已成功从给定的系列对象中选择了 2 行,这 3 行的 DateTime 索引时间介于"00:40"和"1:40"之间,两个时间均不包括在内。


相关文章