Python Pandas dataframe.between_time()
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。
Pandas dataframe.between_time()用于选择一天中特定时间内的数值(例如,9:00-9:30 AM)。与dataframe.at_time()函数不同,该函数提取的是一个时间范围内的值。这个函数只用于时间序列数据。Dataframe的索引必须是DatetimeIndex,以便能够使用这个函数。
语法: DataFrame.between_time(start_time, end_time, include_start=True, include_end=True)
参数:
start_time : datetime.time 或字符串
end_time : datetime.time 或字符串
include_start : boolean, default true
include_end : boolean, default true
返回: values_between_time : 调用者的类型
注意: between_time()函数在数据帧的索引不是DatetimeIndex时引发异常。
例子#1:使用between_time()函数来查找给定时间间隔之间的值。
# importing pandas as pd
import pandas as pd
# Creating row index values for dataframe
# Taken time frequency to be of 30 minutes interval
# Generating eight index value using "period = 8" parameter
ind = pd.date_range('01/01/2000', periods = 8, freq ='30T')
# Creating a dataframe with 2 columns
# using "ind" as the index for dataframe
df = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8],
"B":[10, 20, 30, 40, 50, 60, 70, 80]},
index = ind)
# Printing the dataframe
df
现在我们来查询 “02:00 “到 “03:30 “之间的时间
# Find the row values between time "02:00" to "03:30"
df.between_time('02:00', '03:30')
输出 :
例子#2:使用between_time()函数来查找一个给定时间间隔之间的值,同时排除开始和结束时间。
# importing pandas as pd
import pandas as pd
# Creating row index values for our data frame
# Taken time frequency to be of 30 minutes interval
# Generating eight index value using "period = 8" parameter
ind = pd.date_range('01/01/2000', periods = 8, freq ='30T')
# Creating a dataframe with 2 columns
# using "ind" as the index for our dataframe
df = pd.DataFrame({"A":[1, 2, 3, 4, 5, 6, 7, 8],
"B":[10, 20, 30, 40, 50, 60, 70, 80]},
index = ind)
# query for time between "02:00" to "03:30" with
# both the start and end time values being excluded
df.between_time('02:00', '03:30', include_start = False,
include_end = False)
输出 :
注意开始时间和结束时间所对应的数值并不包括在between_time()函数所返回的数据框中。