[英]Adding and subtracting seconds column from timestamp column pandas
import pandas as pd
import numpy as np
example=[["11/19/20","9:40:28","9:40:00:0","00:00:00.2","101"],
["12/22/20","9:29:28","9:29:28:15", "00:10:28.0","102"],
["2/17/21","9:20:20","9:20:20:2","0:00:05.2","206"]]
example_table= pd.DataFrame(example,columns=["Date","Start_Time","timestamp","Seconds","ID"])
desired_info=[["11/19/20","9:40:28","9:40:00:0","00:00:00.2","101", "9:40:00:2"],
["12/22/20","9:29:28","9:29:28:15", "00:10:28.0","102", "9:40:56:15"],
["2/17/21","9:20:20","9:20:20:2","0:00:05.2","206","9:20:25:4"]]
desired_table= pd.DataFrame(desired_info,columns=["Date","Start_Time","timestamp","Seconds", "CID","Finish_Time"])
# I can convert one of my time columns
example_table.Seconds=example_table.Seconds.apply(pd.to_timedelta)
example_table.Seconds=example_table.Seconds.dt.total_seconds()
example_table['Start_Time']=pd.to_datetime(example_table['Start_Time'], format= '%H:%M:%S').dt.time
最終,我希望能夠將包含毫秒的秒列添加到時間戳列。
當我嘗試以下操作時:
example_table["Finish"]=example_table['timestamp']+example_table['Seconds']
# I get the error:
# can only concatenate str (not "float") to str
因為我越來越絕望,所以我想,也許我可以在計算中使用 Start_Time。
# if I try with the Start_Time column:
["Finish"]=example_table['Start_Time']+example_table['Seconds']
# unsupported operand type(s) for +: 'datetime.time' and 'float'
所以接下來我嘗試使用不同的策略轉換時間戳列。 ```# 當我嘗試轉換時間戳列時,根據策略我會得到許多不同的錯誤
pd.to_timedelta(example_table.timestamp, unit='ms')
#Error: unit must not be specified if the input contains a str
pd.to_timedelta(example_table.timestamp)
#Error: expected hh:mm:ss format```
最后,我將使用完成時間,這實際上是我在另一個實驗中的偏移時間來查找其他信息,如此處所示, 根據另一個 dataframe 查找列的子集?
首先你需要創建一個合適的日期時間 object。
df = example_table
df['desired_date'] = pd.to_datetime(df['Date'] + ' '
+ df['timestamp'],format='%m/%d/%y %H:%M:%S:%f')
然后將Seconds
列轉換為 timesdelta 並將其添加到所需的日期。
我們必須添加一些格式來獲得您的目標字符串格式。
df['desired_date'] = (
df['desired_date']
+
pd.to_timedelta(df['Seconds'])
).dt.strftime('%H:%M:%S:%f').str.rstrip('0')
print(df)
Date Start_Time timestamp Seconds ID desired_date
0 11/19/20 9:40:28 9:40:00:0 00:00:00.2 101 09:40:00:2
1 12/22/20 9:29:28 9:29:28:15 00:10:28.0 102 09:39:56:15
2 2/17/21 9:20:20 9:20:20:2 0:00:05.2 206 09:20:25:4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.