Pandas 数据帧between_time()方法

原文:https://www.studytonight.com/pandas/pandas-dataframe-between_time-method

在本教程中,我们将学习 PandasDataFrame.between_time()方法。此方法选择一天中特定时间之间的值。通过将start_time设置为晚于end_time,可以得到两个时间之间的而不是的时间。它返回数据帧,如果索引不是DataTimeIndex,它将提升TypeError

下图显示了DataFrame.between_time()方法的语法。

句法

DataFrame.between_time(start_time, end_time, include_start=True, include_end=True, axis=None)

因素

start_time: 表示作为时间过滤器限制的初始时间的 datetime.time 或字符串。

end_time: 表示作为时间过滤器限制的结束时间的 datetime.time 或字符串。

include_start: 代表 bool(真或假),默认值为 True。它指示开始时间是否需要包含在结果中。

include_end: 代表 bool(真或假),默认值为 True。表示结果中是否需要包含结束时间。

轴:如果是【0】表示【索引】,如果是【1】表示【列】,默认值为 0。它确定索引或列值的范围时间。

示例 1:从数据帧中获取特定时间之间的值

下面的例子展示了如何通过给DataFrame.between_time()方法提供一个特定的时间来获取行的值。创建一个日期时间索引,并在任何特定时间获取值。

import pandas as pd
Values = pd.date_range('2021-01-01', periods=3, freq='20T')
df = pd.DataFrame({'A': [1, 2, 3],'B': [1, 2, 3]}, index=Values)
print(df)
print("-----Selecting values---------")
print(df.between_time('00:20','1:00'))

一旦我们运行程序,我们将得到以下结果。

A B 2021-01-01 00:00:00 1 1 2021-01-01 00:20:00 2 2 2021-01-01 00:40:00 3 -选择值- A B 2021-01-01 00:20:00 2 2021-01-01 00:40

示例 2:从数据帧中获取特定时间之间的值

下面的例子类似于前面的例子。更改周期和频率值,并从数据帧中获取特定时间之间的值。

import pandas as pd
Values = pd.date_range('2000-01-01', periods=4, freq='1D20min')
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [1, 2, 3, 4]}, index=Values)
print(df)
print("-----Selecting values---------")
print(df.between_time('0:15', '0:45'))

一旦我们运行程序,我们将得到以下结果。

A B 2000-01-01 00:00:00 1 1 2000-01-02 00:20:00 2 2000-01-03 00:40:00 3 2000-01-04 01:00:00 4 -选择值- A B 2000-01-02 00:200

例 3:DataFrame.between_time()方法提升TypeError

如果指数不是DataTimeIndex,DataFrame.between_time()方法会提高TypeError.

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [1, 2, 3, 4]}, index=[1,2,3,4])
print("-----Selecting values---------")
print(df.between_time('00:20','1:00'))

一旦我们运行程序,我们将得到以下结果。

类型错误:索引必须是日期时间索引

例 4: DataFrame.between_time()提升TypeError的方法

下面的例子类似于前面的例子。通过设置axis=1检查DataFrame.between_time()方法。

import pandas as pd
Values = pd.date_range('2000-01-01', periods=4, freq='1D20min')
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [1, 2, 3, 4]}, index=Values)
print(df.between_time('0:15', '0:45',axis=1))

一旦我们运行程序,我们将得到以下结果。

类型错误:索引必须是日期时间索引

示例 5:将 include_start 和 include_end 设置为 False

include_startinclude_endFalse时,我们在结果中得不到开始时间和结束时间。以下示例显示了结果。

import pandas as pd
Values = pd.date_range('2021-01-01', periods=4, freq='20T')
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [1, 2, 3, 4]}, index=Values)
print(df)
print("-----Selecting values---------")
print(df.between_time('00:00','1:00',include_start=False,include_end=False))

一旦我们运行程序,我们将得到以下结果。

A B 2021-01-01 00:00:00 1 1 2021-01-01 00:20:00 2 2 2021-01-01 00:40:00 3 2021-01-01 01:00:00 4 -选择值- A B 2021-01-01 00:24

结论

在本教程中,我们学习了 PandasDataFrame.between_time()方法。我们理解了函数的语法和参数,并通过在数据帧上应用DataFrame.between_time() 方法来获取指定时间之间的值来解决示例。