Datatime 作為 Python 中的時間模塊類型,處理時間有關數據是非常方便的, Pandas 作為數據分析程序包同樣也支持 DataTime 數據機制,例如
1,函數 to_datetime() 將數據列表中的 Series 列轉化為 datetime 類型,
#Convert the type to datetimeapple.Date = pd.to_datetime(apple.Date)apple['Date'].head()#02014-07-0812014-07-0722014-07-0332014-07-0242014-07-01Name: Date, dtype: datetime64[ns]2,DataFrame.resample(freq),將數據基於時間列以 freq 作為頻度做數據重採樣,計算出某隔一段時間中數據總值、均值、方差等指標
下面例子中數據列表的索引就是 Datatime 數據格式,最終計算得到以月為時間單位求出各列數據的平均值
# Resample the data based the offset,get the mean of data# BM — bussiness month end frequencyapple_month = apple.resample("BM").mean()apple_month.head()
下面將根據兩套習題,簡單介紹一下 Pandas 是怎麼使用 DataFrame 數據的
1 , to_datetime() 與 resample() 操作
1.1,讀取數據
url = "https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/09_Time_Series/Apple_Stock/appl_1980_2014.csv"apple =pd.read_csv(url)apple.head()從上面數據中可以看到時間在 Date 這一列,但卻不是標準的 datetime 格式,需要格式處理一下
1.2,datetime 格式轉換
#Convert the type to datetimeapple.Date = pd.to_datetime(apple.Date)apple['Date'].head()
**1.3,將 Date 列設為 index **
需要注意一點的是,後續的 採樣(resample) 操作都是基於 時間列為索引列這一條件的,因此需要索引列設置,
apple = apple.set_index("Date")# Set Indexapple.head()Date 雖然已經設為 index,但是時間排列卻並不清晰,這裡用 sort_index(ascending = True) 直接對其進行正向排序
1.4,對索引進行排序
# Sort The DataFrame based on Date columnsapple.sort_index(ascending = True).head()
1.5,以月為單位對數據採樣並獲取mean()
# Resample the data based the offset,get the mean of data# BM — bussiness month end frequencyapple_month = apple.resample("BM").mean()apple_month.head()
BM 全稱 Bussiness Month,是商業月的意思,在 Pandas 中稱為 DataOffset,除了月之外,還提供年、日、秒、小時、分..等作為採樣單位,當然也可以自定義 DataOffset.
關於 Data Offset 具體詳細內容可參考:https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases;
1.6,計算時間列表中最早日期與最晚日期相差天數
(apple.index.max()-apple.index.min()).days#122612,統計近兩年蘋果、特斯拉、IBM、LINKD各公司股價
2.1,pandas_datareader 獲取數據
import pandas as pdfrom pandas_datareader import data as webimport datetime as dtstart = dt.datetime(2019,1,1)end = dt.datetime.today()stocks = ['APPLE','TSLA','IBM','LNKD']df = web.DataReader(stocks,'yahoo',start,end)df使用之前請確保pandas_datareader 包已經安裝成功,這個包幫助我們直接通過爬蟲獲取近兩年的各公司的股票信息,後面 start,end 兩個 datetime 時間用於限制時間
結果顯示似乎這種方法獲取不到到的蘋果和LINKD 的股價(但並不影響,因為這裡主要是學習一下 datetime 在 Pandas 的用法)
2.2,獲取 股票 數據
vol = df['Volume']vol
**2.3,創建新列,表示 week、year **
後面做聚類分析,聚類基準選擇的是 week、year , 因此需要提前創建好兩列(week,year)數據
vol['week'] = vol.index.weekvol['year'] = vol.index.yearvol.head()
2.4,groupby 聚類分組(先 week ,後 year)
week = vol.groupby(['week','year']).sum()week.head()這樣就可以很清晰地比對,2019-2020年對於每一周來說各公司股票的總值變化啦
好了,以上就是本篇文章的所有內容啦;如果有什麼疑問或者想表達的,歡迎在下面留言區進行留言。
最後,感謝大家的閱讀!
Reference:
1,https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases
2,https://github.com/guipsamora/pandas_exercises/blob/master/09_Time_Series/Getting_Financial_Data