Python Pandas - 返回 DateTimeIndex 中特定时间(包括开始时间)之间的值的索引位置
pythonserver side programmingprogramming更新于 2026/1/19 22:04:17
要返回 DateTimeIndex 中特定时间之间的值的索引位置,请使用 DateTimeIndex.indexer_between_time() 方法。将 include_start 参数设置为 True,以包含开始时间。
首先,导入所需的库 −
import pandas as pd
创建一个 DatetimeIndex,周期为 7,频率为 T,即分钟 −
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
显示 DateTimeIndex −
print("DateTimeIndex...\n", datetimeindex)
显示特定时间之间的值的索引位置。"start_time" 设置为 '02:30:50","end_time" 设置为 '03:20:50"。将include_start参数设置为True −
print("\n特定时间之间的值的索引位置...\n",
datetimeindex.indexer_between_time('03:10:50','03:50:50', include_start = True))
示例
以下是代码 −
import pandas as pd
# DatetimeIndex,周期为7,频率为T,即分钟
# 时区为澳大利亚/阿德莱德
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
# 显示 DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
# 显示 DateTimeIndex 频率
print("\nDateTimeIndex 频率...\n", datetimeindex.freq)
# 显示特定时间的值的索引位置,即此处的 03:10:50
print("\n特定时间的值的索引位置...\n",
datetimeindex.indexer_at_time('2021-10-30 03:10:50'))
# 显示特定时间之间的值的索引位置
# "start_time" 设置为 '02:30:50&39;和"end_time"'03:20:50'
print("\n特定时间之间的值的索引位置...\n",
datetimeindex.indexer_between_time('03:10:50','03:50:50', include_start = True))
输出
这将产生以下代码 −
DateTimeIndex... DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 02:50:50+10:30', '2021-10-30 03:10:50+10:30', '2021-10-30 03:30:50+10:30', '2021-10-30 03:50:50+10:30', '2021-10-30 04:10:50+10:30', '2021-10-30 04:30:50+10:30'], dtype='datetime64[ns, Australia/Adelaide]', freq='20T') DateTimeIndex 频率... <20 * Minutes> 特定时间的值的索引位置... [2] 特定时间之间的值的索引位置... [2 3 4]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

