Pandas 時刻數據 / 時間戳索引 / 時期對象
時刻數據 TimeStamp 👇
時刻數據 代表時間點,是Python的數據類型 pandas.Timestamp 是一個時間戳
import pandas as pd import datetime as dt
Timestamp 的創建 , 時間戳的實例化
date1 = dt.datetime.now() date2 = '2019-10-10 11:30:30' t1 = pd.Timestamp(date1) t2 = pd.Timestamp(date2) print(t1,type(t1)) print(t2,type(t2)) #------輸出-----# 2019-11-05 23:46:38.328008 <class 'pandas._libs.tslibs.timestamps.Timestamp'> 2019-10-10 11:30:30 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
👆 直接實例化。
to_datetime(time) :
👇 to_datetime() 作用和上面的一樣,屬於調用方法實例化, 生成一個Timestamp對象 .
t3 = pd.to_datetime('2019-10-10') t3 #------輸出-----# Timestamp('2019-10-10 00:00:00')
👇 如何一次生成多個,可以選擇用 List (列表) 的方式 :
dates = ['2019-10-10','2019-10-11','2019-10-12','2019-10-13','2019-10-14','2019-10-15','2019-10-16'] t3 = pd.to_datetime(dates) #-----輸出-----# DatetimeIndex(['2019-10-10', '2019-10-11', '2019-10-12', '2019-10-13','2019-10-14', '2019-10-15', '2019-10-16'],dtype='datetime64[ns]', freq=None)
👆 如果是多時間數據,生成的是一個DateTimeIndex ,是一個時間戳的索引,也就是時間索引。時間類型的索引 。
👉 如果生成多個時間數據,列表中夾雜了非 Time 格式的數據 ,默認會報錯 ,它的解決方法就是添加 errors 參數
👉 errors = 'ignore' : 會忽略錯誤,對原數據不可解析 ,返回原始數據,生成的是一個一般的 Index 索引 。
dates = ['2019-10-10','2019-10-11','2019-10-12','abc'] t3 = pd.to_datetime(dates,errors='ignore') #-----輸出-----# Index(['2019-10-10', '2019-10-11', '2019-10-12', 'abc'], dtype='object')
👉 errors = 'coerce' :非Time數據不可解析時,返回Nat值(not a time),生成的對象還是一個 DateTimeIndex
dates = ['2019-10-10','2019-10-11','2019-10-12','abc'] t3 = pd.to_datetime(dates,errors='coerce') #-----輸出-----# DatetimeIndex(['2019-10-10', '2019-10-11', '2019-10-12', 'NaT'], dtype='datetime64[ns]', freq=None)
時間戳索引 DateTimeIndex 👇
# DateTimeIndex 和TimeSeries 時間序列 dts = pd.DatetimeIndex(['2019-10-10','2019-10-11','2019-10-12','2019-10-13']) #-----輸出-----# DatetimeIndex(['2019-10-10', '2019-10-11', '2019-10-12', '2019-10-13'], dtype='datetime64[ns]', freq=None)
👆 直接 生成|實例化 一個 時間序列 DateTimeIndex ,支持類型包括 : str ,datetime.datetime
times = pd.Series(np.random.rand(len(dts)),index=dts) #-----輸出----# 2019-10-10 0.185203 2019-10-11 0.925192 2019-10-12 0.103523 2019-10-13 0.734690 dtype: float64
👆 時間序列,以 DateTimeIndex 為 index 的Series (以時間戳為索引的Series)
👇 pd.date_range() - 時間范圍 , 生成時間范圍列表 ,參數start ,end :
dg = pd.date_range('2019-10-01','2019-10-10') #默認按 '天' 生成 dg1 = pd.date_range(start=dt.datetime.now(),periods=10) #periods 生成時間個數,從開始時間算 dg2 = pd.date_range('2019-10-01','2019-10-05',periods=10) #時長不夠 則按h划分
DatetimeIndex(['2019-10-01', '2019-10-02', '2019-10-03', '2019-10-04', '2019-10-05', '2019-10-06', '2019-10-07', '2019-10-08', '2019-10-09', '2019-10-10'], dtype='datetime64[ns]', freq='D') DatetimeIndex(['2019-11-06 02:30:23.148685', '2019-11-07 02:30:23.148685', '2019-11-08 02:30:23.148685', '2019-11-09 02:30:23.148685', '2019-11-10 02:30:23.148685', '2019-11-11 02:30:23.148685', '2019-11-12 02:30:23.148685', '2019-11-13 02:30:23.148685', '2019-11-14 02:30:23.148685', '2019-11-15 02:30:23.148685'], dtype='datetime64[ns]', freq='D') DatetimeIndex(['2019-10-01 00:00:00', '2019-10-01 10:40:00', '2019-10-01 21:20:00', '2019-10-02 08:00:00', '2019-10-02 18:40:00', '2019-10-03 05:20:00', '2019-10-03 16:00:00', '2019-10-04 02:40:00', '2019-10-04 13:20:00', '2019-10-05 00:00:00'], dtype='datetime64[ns]', freq=None)
date_range() 的一些參數說明 :
# start : 開始時間 # end : 結束時間 # periods : 生成時間數量 # freq : 頻率 按頻率生成 設置為s 為秒 ,h ,d ,m , y # normalize : 轉換成午夜時間 設置為True 時,默認去除 時分秒 # closed : 時期區間的閉合 closed ='left' 左閉合 默認為None 全閉
時間頻率 timeseries.offset_aliases -- freq 參數 :
# 常見常用參數 : # freq 默認為"D" 每天 # B 每個工作日 # H 每小時 # M 每個月的最后一天 # T T/Min 每分鍾 # Q-DEC 指定某月為季度末,每個季度的最后一個月的最后一日 # S 每秒鍾 # L 每毫秒 (千分之一秒) # U 每微秒 (百萬分之一秒)
print(pd.date_range('2019/1/1','2019/2/1',freq='W-Mon')) #-----輸出-----# DatetimeIndex(['2019-01-07', '2019-01-14', '2019-01-21', '2019-01-28'], dtype='datetime64[ns]', freq='W-MON')
👆 W-MON :從指定星期幾開始算起,每周的星期幾
👆 星期幾縮寫 : mon / tue / wed / thu / fri / sat / sun
print(pd.date_range('2019/1/1','2019/5/1',freq='WOM-2MON')) #-----輸出-----# DatetimeIndex(['2019-01-14', '2019-02-11', '2019-03-11', '2019-04-08'], dtype='datetime64[ns]', freq='WOM-2MON')
👆 WON-2MON ,每月的第幾個星期幾開始算,這里是每月第二個星期一
復合頻率 話不多說,直接看例子 :
ad = pd.date_range('2019-10-10','2019-10-31',freq='7D') # 每隔7天生成一個 #------輸出-----# DatetimeIndex(['2019-10-10', '2019-10-17', '2019-10-24', '2019-10-31'], dtype='datetime64[ns]', freq='7D') ad = pd.date_range('2019-10-10','2019-10-11',freq='2H30MIN') #每隔2h30min生成一個 #-----輸出-----# DatetimeIndex(['2019-10-10 00:00:00', '2019-10-10 02:30:00', '2019-10-10 05:00:00', '2019-10-10 07:30:00', '2019-10-10 10:00:00', '2019-10-10 12:30:00', '2019-10-10 15:00:00', '2019-10-10 17:30:00', '2019-10-10 20:00:00', '2019-10-10 22:30:00'], dtype='datetime64[ns]', freq='150T')
時刻頻率的改變 : 例如 :
ts = pd.Series(np.random.rand(5),index=pd.date_range('2019-1-1',periods=5,freq='H')) #-----輸出-----# 2019-01-01 00:00:00 0.235263 2019-01-01 01:00:00 0.116529 2019-01-01 02:00:00 0.475352 2019-01-01 03:00:00 0.285782 2019-01-01 04:00:00 0.278366 Freq: H, dtype: float64
👆 如何把 上方的頻率 H 降頻 為min , s 或者其他呢? 用 .asfreq() 方法
ts.asfreq('2H') #-----輸出-----# 2019-01-01 00:00:00 235.263032 2019-01-01 02:00:00 475.352441 2019-01-01 04:00:00 278.366048 Freq: 2H, dtype: float64 ts.asfreq('30min') #-----輸出-----# 2019-01-01 00:00:00 235.263032 2019-01-01 00:30:00 NaN 2019-01-01 01:00:00 116.529416 2019-01-01 01:30:00 NaN 2019-01-01 02:00:00 475.352441 2019-01-01 02:30:00 NaN 2019-01-01 03:00:00 285.781654 2019-01-01 03:30:00 NaN 2019-01-01 04:00:00 278.366048 Freq: 30T, dtype: float64
👆 當超頻時,默認為NaN,通過 method = 'ffill' 時 向前填充 , bfill 時向后填充.
超前 和 滯后 :數據值相對索引自定義向前后移動 : .shift()
ts.shift(1) #-----輸出-----#
2019-01-01 00:00:00 NaN 2019-01-01 01:00:00 0.517237 2019-01-01 02:00:00 0.152740 2019-01-01 03:00:00 0.790932 2019-01-01 04:00:00 0.988369
Freq: H, dtype: float64
👆 : 值為正數 值往后面挪動 , 值為負數 值往前挪動 .也可以理解為時間移動了,其實是值移動了.
👆 : 有個很強大的功能,例如 : 計算當前值和上一次值的變化百分比
ts = ts * 1000 print(ts/ts.shift(1)-1) #-----輸出-----# 2019-01-01 00:00:00 NaN 2019-01-01 01:00:00 -0.504685 2019-01-01 02:00:00 3.079248 2019-01-01 03:00:00 -0.398800 2019-01-01 04:00:00 -0.025949 Freq: H, dtype: float64
## 解釋 :
具體的意思就是第二天相比比第一天相比增長還是下降 ,每天的增降再Sum一下便能得到整個月的數值與上月比較漲幅 。 (今天的值除以昨天的值的再減百分之百)
移動時間 .shift() +freq :

print(ts) ts.shift(-30,freq="T") #-----輸出-----# 2019-01-01 00:00:00 59.981144 2019-01-01 01:00:00 39.215781 2019-01-01 02:00:00 62.647637 2019-01-01 03:00:00 57.058369 2019-01-01 04:00:00 84.421470 Freq: H, dtype: float64 2018-12-31 23:30:00 59.981144 2019-01-01 00:30:00 39.215781 2019-01-01 01:30:00 62.647637 2019-01-01 02:30:00 57.058369 2019-01-01 03:30:00 84.421470 Freq: H, dtype: float64
👆 加上參數 freq 代表移動時間索引 整體移動, #不添加freq 值移動,添加freq 時間移動#
時期對象 Period 👇
創建一個 Period 對象
pd.Period('2019',freq='2M') #-----輸出-----# Period('2019-01', '2M')
👆 這是一個以2019-01開始,月為頻率的時間構造器
👆 pd.Period參數 : freq 👉 指明該 period 的長度 ,時間戳說明時間的具體位置
時期~范圍 pd.period_range() :
pd.period_range('2019-1-1','2019-10-1',freq='M') #-----輸出-----# PeriodIndex(['2019-01', '2019-02', '2019-03', '2019-04', '2019-05', '2019-06', '2019-07', '2019-08', '2019-09', '2019-10'], dtype='period[M]', freq='M')
👆 返回的是一個periodIndex 對象 : 時期索引對象
pd.Series(np.random.rand(10),index=perd) #-----輸出-----# 2019-01 0.512124 2019-02 0.289445 2019-03 0.337499 2019-04 0.828296 2019-05 0.574218 2019-06 0.290252 2019-07 0.806585 2019-08 0.233860 2019-09 0.833617 2019-10 0.143754 Freq: M, dtype: float64
Timestamp 表示一個時間戳 ,表示一個具體的時間
Period 表示一個時期 ,一個時間段。 作為索引來說,區別不大!
# 頻率的轉換 ,下面展示的是 由M 轉 D :
perd.asfreq('D',how='S') #-----輸出-----# PeriodIndex(['2019-01-01', '2019-02-01', '2019-03-01', '2019-04-01', '2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01', '2019-10-01'], dtype='period[D]', freq='D')
how =' S' 指定第一個值 S 代表 開始 Start ,E 代表末尾 End
時間戳 和 時期之間 的轉換 , pd.to_period , pd.to_timestamp
pt = pd.period_range('2018','2019',freq='M') st = pd.date_range('2019/1/1',periods=10,freq='MS') pts = pd.Series(np.random.rand(len(pt)),index=pt) pts.to_timestamp #每月的最后一日,轉換成每日 sts = pd.Series(np.random.rand(len(st)),index=st) sts.to_period #每月,轉換為每月的第一天

<bound method Series.to_timestamp of 2018-01 0.910903 2018-02 0.582622 2018-03 0.942149 2018-04 0.849428 2018-05 0.866768 2018-06 0.840774 2018-07 0.085061 2018-08 0.963129 2018-09 0.256044 2018-10 0.727409 2018-11 0.043810 2018-12 0.544194 2019-01 0.030864 Freq: M, dtype: float64> <bound method Series.to_period of 2019-01-01 0.699750 2019-02-01 0.685037 2019-03-01 0.218881 2019-04-01 0.811947 2019-05-01 0.102095 2019-06-01 0.869153 2019-07-01 0.654644 2019-08-01 0.792193 2019-09-01 0.179387 2019-10-01 0.855273 Freq: MS, dtype: float64>