Python Pandas – 返回特定时间段内DateTimeIndex中的值的索引位置

Python Pandas – 返回特定时间段内DateTimeIndex中的值的索引位置

要返回特定时间段内DateTimeIndex中的值的索引位置,请使用 DateTimeIndex.indexer_between_time() 方法。

首先,导入所需的库−

import pandas as pd

创建一个周期为5、频率为T(即分)的DatetimeIndex。时区为Australia / Adelaide−

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, tz='Australia/Adelaide', freq='20T')

显示DateTimeIndex−

print("DateTimeIndex...\n", datetimeindex)

显示特定时间段内的值的索引位置。 “start_time”设置为’02: 30: 50’,”end_time”设置为’03: 20: 50−

print("\n特定时间段内的值的索引位置...\n",
datetimeindex.indexer_between_time('02:30:50','03:20:50'))

示例

以下是代码−

import pandas as pd

# 创建周期为5、频率为T的DatetimeIndex。时区为Australia / Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=5, 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',"end_time"设置为'03: 20: 50'
print("\n特定时间段内的值的索引位置...\n",
datetimeindex.indexer_between_time('02:30:50','03:20:50'))

输出

程序会产生以下代码−

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'],
dtype ='datetime64 [ns,Australia / Adelaide]',freq ='20T')
DateTimeIndex的频率...
<20 *分钟>

特定时间点的值的索引位置...
[2]

特定时间段内的值的索引位置...
[0 1 2]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程