簡體   English   中英

獲取 python 中時間序列的小時數

[英]Get the time in hours of a time-series in python

這似乎是一個瑣碎的問題:我有一個數據點列表,每 5 分鍾記錄一次,重疊 2.5 分鍾(2 分半鍾)。 我還有記錄開始的時間戳和另一個我需要開始計算時間的時間戳(例如計時器開始): 在此處輸入圖像描述

我需要計算從計時器開始到錄音結束已經過去了多少小時,並制作一個 dataframe,其中一列中我有錄音,而在另一列中是從該錄音所屬的計時器開始的小時數:例如

記錄 從計時器開始的小時數
0.262 0
0.243 0
0.263 0
0.342 1個
0.765 1個
0.111 1個
... ...

這就是我在 python 中的做法:

import numpy as np
import pandas as pd
from math import floor

recordings = list(np.random.rand(1000)) # an example of recording

chronometer_start = 1670000000 #timestamp
start_recording = 1673280570 #timestamp
gap_in_seconds = start_recording - chronometer_start

# given that the recordings are of 5 minutes each but with 2.5 minutes overlap,
# I can calculate how many Null values to add at the beginning of the recording to
# fill the gap from the chronometer start:
gap_in_n_records = round(gap_in_seconds / 60 / 2.5)

# fill the gap with null values
recordings = [np.nan for _ in range(gap_in_n_records)] + recordings 

minutes = [5] # the first recording has no overlap
for _ in range(len(recordings)-1):
    minutes += [minutes[-1]+2.5]
hours = pd.Series(minutes).apply(lambda x: floor(x/60))

df = pd.DataFrame({
    'recording' : recordings,
    'hour' : hours
})

但我擔心我犯了一些錯誤,因為我的數據與我的結果不一致。 有更好的方法嗎?

首先,總結一下,看看我是否理解正確。 您擁有在某個時間點(可能是幾天/幾周前)開始的計時器,並且您的數據點都需要五分鍾。 您正在尋找數據點結束的小時(計時碼表開始后)。

對於前 5 條記錄:

記錄索引 錄音開始后分鍾
1個 5個
2個 7.5
3個 10
4個 12.5
5個 15

所以我們可以將其總結為公式:

數據點 n 的記錄開始后經過的時間(以分鍾為單位):5 + (n-1) * 2.5

我們可以使用這個公式和 DataFrame 的索引來計算自錄音開始以來經過的時間,然后加上錄音開始和計時開始之間經過的時間:

import numpy as np
import pandas as pd

df = pd.DataFrame({"recordings": np.random.rand(1000)})

chronometer_start = 1670000000  # timestamp
start_recording = 1673280570  # timestamp
gap_in_seconds = start_recording - chronometer_start  

# since the index of a pandas DataFrame starts at 0, we can make use of that (idx=n-1)
df["seconds_passed_since_chronometer_start"] = 5 + df.index * (2.5 * 60) + (gap_in_seconds) 

# assuming that the first hour after the chronometer starts is hour 0, the column would be: 
df["hours"] = df["seconds_passed_since_chronometer_start"].apply(lambda x: int(x) // 3600)

final_df = df[["recordings", "hours"]]

暫無
暫無

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

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