Pandas 如何从系列中获取特定时间段的值

Pandas 如何从系列中获取特定时间段的值

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

# create the index
index = pd.date_range('2021-01-1', periods=10, freq='20T')

#creating pandas Series with date time index
series = pd.Series([1,2,3,4,5,6,7,8,9,10], index=index)

print(series)

# selecting values by 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”时间段之间的数值。在这个示例中,起始时间(“00:10”)和结束时间(“1:40”)都是包含在内的。

示例2

import pandas as pd

# create the index
index = pd.date_range('2021-01-1', periods=10, freq='20T')

#creating pandas Series with date time index
series = pd.Series([1,2,3,4,5,6,7,8,9,10], index=index)

print(series)

# selecting values by between_time()
print("Selecting values:", series.between_time("00:40","1:40", include_start=False,include_end=False))

说明

在下面的示例中,我们通过不包括起始时间和结束时间来使用between_time()方法,这是通过向include_start和include_end参数提供False值来实现的。

输出

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行的日期时间索引在“00:40”和“1:40”之间,两个时间都不包括在内。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程

Pandas 精选笔记