我有一個包含 2 列的時間序列,第一列是 1970 年 1 月 1 日之后的幾個小時。在此列中,一年只有 360 天,其中 12 個月為 30 天。我需要將此列轉換為可用日期,以便我可以根據月、年等分析另一列(例如,1997-Jan-1-1 是年-月-日-小時)。
我需要用模數創建一個陣列,將小時列的每一行轉換為hour_of_day、day_of_month、year 等,以便該列改為年、月、日和小時。但我不知道如何做到這一點。欣賞它可能會令人困惑。任何有關這樣做的幫助都會非常有幫助。
Input: 233280.5 (in hours)
Output: 1997-01-01-01 (year-day-month-hour)
uj5u.com熱心網友回復:
您可以計算年數并將其添加到參考日期,例如
import pandas as pd
import numpy as np
from pandas.tseries.offsets import DateOffset
refdate = pd.Timestamp('1970-01-01')
df = pd.DataFrame({'360d_year_hours': [233280.5]})
# we calculate the number of years and fractional years as helper Series
y_frac, y = np.modf(df['360d_year_hours'] / (24*360))
# now we can calculate the new date's year:
df['datetime'] = pd.Series(refdate DateOffset(years=i) for i in y)
# we need the days in the given year to be able to use y_frac
daysinyear = np.where(df['datetime'].dt.is_leap_year, 366, 365)
# ...so we can update the datetime and round to the hour:
df['datetime'] = (df['datetime'] pd.to_timedelta(y_frac*daysinyear, unit='d')).dt.round('h')
# df['datetime']
# 0 1997-01-01 01:00:00
# Name: datetime, dtype: datetime64[ns]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383427.html
上一篇:如何使用for回圈創建此函式?
下一篇:python提供同步緩沖區嗎?
