在Python Pandas中比较时间戳
Pandas的timestamp相当于Python中的DateTime。时间戳用于pandas中面向时间序列的数据结构。有时,日期和时间在pandas中被提供为时间戳,或者有利于被转换为时间戳。而且,需要对时间戳进行比较,以了解最新的条目、两个时间戳之间的条目、最旧的条目等等,以完成各种任务。pandas时间戳对象之间的比较是通过简单的比较运算符进行的。< = , >差额可以用简单的’-‘运算符来计算</=>,比如:>, <, ==< = , >,</=>=.< = , > </=>
给定的时间可以通过pandas.Timestamp()方法转换为pandas时间戳。这个方法可以接受各种形式的输入,如类似DateTIME的字符串(如’2017-01-01T12’),以秒为单位的Unix纪元(1513393355.5),等等。这些值可以取为年、月、日、时、分、秒等,用逗号分隔或使用变量名。例如,如果我们想写2018/2/21 11:40:00,我们可以提供(2018,2,21,11,40)作为参数给Timestamp方法或者可以写(年=2018,月=2,日=21,小时=11,分钟=40)。没有提供的值将被认为是零。在下面的代码中使用了这种方法,使用提供的日期和时间信息创建时间戳列 “new_time”。
方法:
- 创建一个带有日期和时间值的数据框架
- 使用pandas.timestamp()方法将日期和时间值转换成时间戳值
- 使用常规比较运算符比较所需的时间戳。
创建一个带有日期和时间的pandas Dataframe:
import pandas as pd
# Create a dataframe
df = pd.DataFrame({
'year': [2017, 2017, 2017, 2018, 2018],
'month': [11, 11, 12, 1, 2],
'day': [29, 30, 31, 1, 2],
'hour': [10, 10, 10, 11, 11],
'minute': [10, 20, 25, 30, 40]})
def time(rows):
return (pd.Timestamp(rows.year, rows.month,
rows.day, rows.hour, rows.minute))
# Create new column with entries of date
# and time provided in timestamp format
df['new_time'] = df.apply(time, axis = 'columns')
display(df)
输出:
在以下例子中使用了上述df。
例子1:这里,”new_time “中的第一个和第二个时间戳被比较,以了解其中最古老的时间。
# Compare first and second timestamps
if df['new_time'][0] <= df['new_time'][1]:
print("First entry is old")
else:
print("Second entry is old")
输出:
First entry is old
示例2:这里,’new_time’中的所有时间戳都与Timestamp(2018-01-05 12:00:00)进行比较,并返回这个时间戳之前的条目
# Timestamps satisfying given condition
for i in range(len(df['year'])):
if df['new_time'][i] < pd.Timestamp(2018, 1, 5, 12):
print(df['new_time'][i])
输出:
2017-11-29 10:10:00
2017-11-30 10:20:00
2017-12-31 10:25:00
2018-01-01 11:30:00
示例3:这里我们再次用Timestamp(2018-01-05 12:00:00)比较了所有的时间戳,但对所有的时间戳都以布尔值(真/假)的形式返回比较结果。
# Boolean value output for given condition
print(df['new_time'] > pd.Timestamp(2018, 1, 5, 12))
输出:
0 False
1 False
2 False
3 False
4 True
Name: new_time, dtype: bool
例子4:这里,max函数被用来获取所有时间戳的最大值,也就是’new_time’列中的最近条目。
此外,我们还在’new_time’列中计算了第一个和第二个时间戳之间的时间差。
# Latest timestamp
print("Latest Timestamp: ", max(df['new_time']))
# Get difference between 2 timestamps
diff = abs(df['new_time'][0]-df['new_time'][1])
print("Difference: ", diff)
输出:
Latest Timestamp: 2018-02-02 11:40:00
Difference: 1 days 00:10:00