簡體   English   中英

將時間四舍五入到最近的小時 pandas 系列

[英]Round the time up to the nearest hour pandas Series

試圖將觀察到的時間四舍五入到最接近的小時

Example Data: 
observed_time = ['2020-02-20T17:54:00Z', '2020-02-20T18:54:00Z']

slice_begin_time=['2020-02-20T17:50:00Z', '2020-02-20T18:50:00Z', '2020-02-20T19:50:00Z', '2020-02-20T20:50:00Z', '2020-02-20T21:50:00Z']
slice_end_time=['2020-02-20T18:05:00Z', '2020-02-20T19:05:00Z', '2020-02-20T20:05:00Z', '2020-02-20T21:05:00Z', '2020-02-20T22:05:00Z']

### LIBS
from datetime import datetime, timedelta
import pandas as pd

s = pd.Series(pd.to_datetime(observed_time))
for i in range(len(slice_begin_time)):
    s[s.between(pd.Timestamp(slice_begin_time[i]),pd.Timestamp(slice_end_time[i]))] == s.round(freq = 'H')
print(s)

我收到錯誤錯誤:round() 得到了一個意外的關鍵字參數 'freq'

我確實想要一個系列。

希望這可以幫助:

observed_time = ['2020-02-20T17:54:00Z', '2020-02-20T18:54:00Z']

slice_begin_time=['2020-02-20T17:50:00Z', '2020-02-20T18:50:00Z', '2020-02-20T19:50:00Z', '2020-02-20T20:50:00Z', '2020-02-20T21:50:00Z']
slice_end_time=['2020-02-20T18:05:00Z', '2020-02-20T19:05:00Z', '2020-02-20T20:05:00Z', '2020-02-20T21:05:00Z', '2020-02-20T22:05:00Z']

def match(time):
    for i in range(len(slice_begin_time)):
        if pd.Timestamp(slice_begin_time[i]) <= time <= pd.Timestamp(slice_end_time[i]):
            return time.round('1H')
            break
    return time  # returns the input time in case nothing matches

s = pd.Series(pd.to_datetime(observed_time))
# apply map function match to the series elements    
s = s.map(match)
print(s)

輸出:

0   2020-02-20 18:00:00+00:00
1   2020-02-20 19:00:00+00:00
dtype: datetime64[ns, UTC]

如果您只是想將時間序列轉換為最近的小時,您可以使用:

s = s.dt.round('1H')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM