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,以上就是分析時序數據的一些常用的方法,希望給讀者帶來幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章