簡體   English   中英

Python:將秒數轉換為數據幀列中的日期時間格式

[英]Python: Converting a seconds to a datetime format in a dataframe column

目前我正在使用一個大數據框(12x47800)。 十二列之一是由整數秒組成的列。 我想將此列更改為由 datetime.time 格式組成的列。 Schedule 是我的數據框,我在其中嘗試更改名為“depTime”的列。 因為我希望它是一個 datetime.time 並且它可能跨越午夜,所以我添加了 if 語句。 這“有效”,但確實像人們想象的那樣慢。 有沒有更快的方法來做到這一點? 我當前的代碼,我唯一可以工作的是:

for i in range(len(schedule)):
    t_sec = schedule.iloc[i].depTime
    [t_min, t_sec] = divmod(t_sec,60)
    [t_hour,t_min] = divmod(t_min,60)
    if t_hour>23:
        t_hour -= 23
    schedule['depTime'].iloc[i] = dt.time(int(t_hour),int(t_min),int(t_sec))

在此先感謝各位。

Ps:我對 Python 還很陌生,所以如果有人能幫助我,我將不勝感激 :)

我正在添加一個比原始解決方案快得多的新解決方案,因為它依賴於熊貓矢量化函數而不是循環(熊貓應用函數本質上是對數據進行優化的循環)。

我使用與您的大小相似的樣本對其進行了測試,差異是從 778 毫秒到 21.3 毫秒。 所以我絕對推薦新版本。

這兩種解決方案都基於將秒整數轉換為 timedelta 格式並將其添加到參考日期時間。 然后,我只是捕獲生成的日期時間的時間部分。

新(更快)選項:

import datetime as dt

seconds = pd.Series(np.random.rand(50)*100).astype(int) # Generating test data

start = dt.datetime(2019,1,1,0,0) # You need a reference point

datetime_series = seconds.astype('timedelta64[s]') + start

time_series = datetime_series.dt.time

time_series

原始(較慢)答案:

不是最優雅的解決方案,但它確實有效。

import datetime as dt

seconds = pd.Series(np.random.rand(50)*100).astype(int) # Generating test data

start = dt.datetime(2019,1,1,0,0) # You need a reference point

time_series = seconds.apply(lambda x: start + pd.Timedelta(seconds=x)).dt.time

您應該盡量不要對數據幀進行全面掃描,而是使用矢量化訪問,因為它通常效率更高。

幸運的是,pandas 有一個函數可以完全滿足您的要求, to_timedelta

schedule['depTime'] = pd.to_timedelta(schedule['depTime'], unit='s')

這是不是一個真正的日期時間格式,但它是一個等價的大熊貓datetime.timedelta ,是一種方便型的處理時間。 您可以使用to_datetime但將以接近 1970-01-01 的完整日期時間結束...

如果你真的需要datetime.time對象,你可以這樣得到它們:

schedule['depTime'] = pd.to_datetime(schedule['depTime'], unit='s').dt.time

但它們在熊貓數據框中使用起來不太方便。

暫無
暫無

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

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