1. 程式人生 > >Python時間序列處理之datetime與pandas模組

Python時間序列處理之datetime與pandas模組

每次遇到時間型別的資料做處理的時候,我會非常頭疼,我忍無可忍之下決定硬著頭皮學習一下,發現也不是很複雜,掌握一些基礎方法就可以做,下面我將一一介紹這些有效的方法。

datetime模組

#匯入datetime包
import datetime

#獲取當前時間
now = datetime.now()
print(now)

#格式化輸出一下
print('年: {}, 月: {}, 日: {}'.format(now.year, now.month, now.day))

#算時間差
diff = datetime(2018, 8, 20, 17) - datetime(2017, 7, 20
, 15) print(diff)

字串和datetime轉換

#datetime轉string
dt_obj = datetime(2018, 8, 20)
str_obj = str(dt_obj)
print(type(str_obj))
print(str_obj)

#string轉datetime
dt_str = '2018-08-20'
dt_obj2 = datetime.strptime(dt_str, '%Y-%m-%d')#必須是這種形式否則會報錯
print(type(dt_obj2))
print(dt_obj2)

dateutil解析

#匯入包
from dateutil.parser import parse
dt_str2 = '2018/08/20'
#可以是各種可以被解析的格式 dt_obj3 = parse(dt_str2) print(type(dt_obj3)) print(dt_obj3)

pandas的datetime

#將一組轉化為時間型別
import pandas as pd
s_obj = pd.Series(['2018/08/18', '2018/08/19', '2018-08-25', '2018-08-26'])
s_obj2 = pd.to_datetime(s_obj)
print(s_obj2)

pandas的時間序列處理

#匯入包
from datetime import datetime
import pandas as pd
import numpy as np

#將index變為datetime的列表形式(這樣會讓處理變得十分方便)
date_list = [datetime(2018, 2, 18), datetime(2018, 2, 19), datetime(2018, 2, 25), datetime(2018, 2, 26), datetime(2018, 3, 4), datetime(2018, 3, 5)] time_s = pd.Series(np.random.randn(len(date_list)), index=date_list) print(times_s) #pd.date_range()生成一組日期 dates = pd.date_range('2018-08-18', # 起始日期 periods=5, # 週期 freq='W-SAT') # 頻率(週六開始) print(dates) print(pd.Series(np.random.randn(5), index=dates)) #索引,index為時間之後,索引變得很方便 #傳入可被解析的字串 print(time_s['2018/08/18']) #傳入年月 print(time_s['2018-8']) #切片與過濾 print(time_s['2018-8-19':]) print(time_s.truncate(before='2018-8-20')) print(time_s.truncate(after='2017-8-20')) #還可以這樣生成日期 time = pd.date_range('2018/08/18', '2018/08/28', freq='2D')#freq是頻率,2D代表兩天,可以3D,5D...... #shift移動資料 ts = pd.Series(np.random.randn(5), index=pd.date_range('20180818', periods=5, freq='W-SAT')) print(ts) #後移 print(ts.shift(1)) #前移 print(ts.shift(-1))

時間資料重取樣resample(重點)

import pandas as pd
import numpy as np

#資料生成
date_rng = pd.date_range('20180101', periods=100, freq='D')
ser_obj = pd.Series(range(len(date_rng)), index=date_rng)
print(ser_obj.head(10))

#按月求和
resample_month_sum = ser_obj.resample('M').sum()
#按月求平均
resample_month_sum = ser_obj.resample('M').mean()
print(resample_month_sum)
#還可以按5天或者10天......
resample_month_sum = ser_obj.resample('5D').sum()
resample_month_sum = ser_obj.resample('10D').mean()

#以上做的其實是降取樣,也就是將長時間間隔變為短的來處理一些資料,比如從月為間隔變為天為間隔,進行求和平均等待,其實還可升取樣,但是會存在缺失資料的問題,可以通過一些方式來彌補缺失資料。

#升取樣以及缺失資料處理
#按周生成資料
df = pd.DataFrame(np.random.randn(5, 3),
                 index=pd.date_range('20180101', periods=5, freq='W-MON'),
                 columns=['S1', 'S2', 'S3'])
print(df)
#按天升取樣
print(df.resample('D').asfreq())
#前補資料,將缺失資料補全為前面的資料
print(df.resample('D').ffill(2))#補兩個,不指定數字全補全
#後補
print(df.resample('D').bfill())
#擬合補資料
print(df.resample('D').fillna('ffill'))#做線性擬合

時間序列資料統計——滑動視窗

import pandas as pd
import numpy as np

#生成資料
ser_obj = pd.Series(np.random.randn(1000), 
                    index=pd.date_range('20180101', periods=1000))
ser_obj = ser_obj.cumsum()#累加
print(ser_obj.head())

#rolling滑動
r_obj = ser_obj.rolling(window=5)#視窗為5
print(r_obj)
print(r_obj.mean())#求均值,即第五個資料是前五個資料的均值,以此類推

# 畫圖檢視
import matplotlib.pyplot as plt

#pandas直接plot,很方便,index預設是x,這也能看出index設定為時間序列的好處
ser_obj.plot(style='r--')
ser_obj.rolling(window=10).mean().plot(style='b')
plt.show()

ok,以上就是分析時序資料的一些常用的方法,希望給讀者帶來幫助。