Python Pandas - 返回一天中特定时间之间值的索引位置,包括 DateTimeIndex 中的开始时间
要返回DateTimeIndex中特定时间之间值的索引位置,请使用该方法。将include_start参数设置为True以包含开始时间。DateTimeIndex.indexer_between_time()
首先,导入所需的库-
import pandas as pd
创建一个日期时间索引,周期为7,频率为T即分钟-
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')显示日期时间索引-
print("DateTimeIndex...\n", datetimeindex)显示一天中特定时间之间值的索引位置。“start_time”设置为“02:30:50”,“end_time”设置为“03:20:50”。将include_start参数设置为True-
print("\nIndex locations of values between particular time of day...\n",
datetimeindex.indexer_between_time('03:10:50','03:50:50', include_start = True))示例
以下是代码-
import pandas as pd
#DatetimeIndexwithperiod7andfrequencyasTi.e.minutes
#ThetimezoneisAustralia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='20T')
#displayDateTimeIndex
print("DateTimeIndex...\n", datetimeindex)
#displayDateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
#displayindexlocationsofvaluesatparticulartimeofdayi.e.03:10:50here
print("\nIndex locations of values at particular time of day...\n",
datetimeindex.indexer_at_time('2021-10-30 03:10:50'))
#displayindexlocationsofvaluesbetweenparticulartimeofday
# The "start_time" is set '02:30:50' and "end_time" '03:20:50'
print("\nIndex locations of values between particular time of day...\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 frequency... <20 * Minutes> Index locations of values at particular time of day... [2] Index locations of values between particular time of day... [2 3 4]
