通过Python Pandas寻找时间戳之间的差异
要找到时间戳之间的差异,我们可以使用索引运算符即方括号来查找差异。对于时间戳,我们还需要使用abs()。首先,导入所需的库−
import pandas as pd
创建一个具有3列的DataFrame。我们有两个带时间戳的日期列−
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],
"Date_of_Purchase": [
pd.Timestamp("2021-06-10"),
pd.Timestamp("2021-07-11"),
pd.Timestamp("2021-06-25"),
pd.Timestamp("2021-06-29"),
pd.Timestamp("2021-03-20"),
],
"Date_of_Service": [
pd.Timestamp("2021-11-10"),
pd.Timestamp("2021-12-11"),
pd.Timestamp("2021-11-25"),
pd.Timestamp("2021-11-29"),
pd.Timestamp("2021-08-20"),
]
})
现在,让我们找到来自两个日期列的时间戳之间的差异−
timestamp_diff = abs(dataFrame ['Date_of_Purchase'] - dataFrame ['Date_of_Service'])
示例
以下是代码−
import pandas as pd
# 创建一个具有3列的DataFrame
dataFrame = pd.DataFrame(
{
"Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],
"Date_of_Purchase": [
pd.Timestamp("2021-06-10"),
pd.Timestamp("2021-07-11"),
pd.Timestamp("2021-06-25"),
pd.Timestamp("2021-06-29"),
pd.Timestamp("2021-03-20"),
],
"Date_of_Service": [
pd.Timestamp("2021-11-10"),
pd.Timestamp("2021-12-11"),
pd.Timestamp("2021-11-25"),
pd.Timestamp("2021-11-29"),
pd.Timestamp("2021-08-20"),
]
}
)
print "DataFrame...\n", dataFrame
# 寻找时间戳之间的差异
timestamp_diff = abs(dataFrame ['Date_of_Purchase'] - dataFrame ['Date_of_Service'])
print"\nDifference between two Timestamps: \n",timestamp_diff
输出
这将产生以下输出−
DataFrame...
Car Date_of_Purchase Date_of_Service
0 Audi 2021-06-10 2021-11-10
1 Lexus 2021-07-11 2021-12-11
2 Tesla 2021-06-25 2021-11-25
3 Mercedes 2021-06-29 2021-11-29
4 BMW 2021-03-20 2021-08-20
Difference between two Timestamps:
0 153 days
1 153 days
2 153 days
3 153 days
4 153 days
dtype: timedelta64[ns]