我有一個帶有以下列的 Pandas DataFrame (first column = index):
0 14:43:45:921
1 14:43:45:923
2 14:43:45:925
我想修改此列,或添加另一列,時間從以下位置開始0:
0 00:00:00.000
1 00:00:00.002
2 00:00:00.004
到目前為止,我已經嘗試了以下代碼:
df['time'].apply(pd.Timedelta)
這給了我以下錯誤:
expected hh:mm:ss format
對我來說,問題是
a) 將時間格式轉換HH:MM:SS:fff為HH:MM:SS.fff和
b) 使timedelta函式作業。
有沒有人有什么建議?謝謝!
uj5u.com熱心網友回復:
使用to_datetime:
s = pd.to_datetime(df['time'], format='%H:%M:%S:%f')
或Series.str.replace與to_timedelta:
s = pd.to_timedelta(df['time'].str.replace('(:)(\d )$', r'.\2'))
然后減去第一個值:
df['new'] = s.sub(s.iat[0])
print (df)
time new
0 14:43:45:921 0 days 00:00:00
1 14:43:45:923 0 days 00:00:00.002000
2 14:43:45:925 0 days 00:00:00.004000
如果需要時間:
df['new'] = s.sub(s.iat[0])
df['new1'] = df['new'].apply(lambda x: (pd.datetime.min x).time())
print (df)
time new new1
0 14:43:45:921 0 days 00:00:00 00:00:00
1 14:43:45:923 0 days 00:00:00.002000 00:00:00.002000
2 14:43:45:925 0 days 00:00:00.004000 00:00:00.004000
print (type(df.at[0, 'new']))
<class 'pandas._libs.tslibs.timedeltas.Timedelta'>
print (type(df.at[0, 'new1']))
<class 'datetime.time'>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/381291.html
