1. 程式人生 > >Pandas 資料處理 | Datetime 在 Pandas 中的一些用法!

Pandas 資料處理 | Datetime 在 Pandas 中的一些用法!

Datatime 是 Python 中一種時間資料型別,對於不同時間格式之間的轉換是比較方便的,而在 Pandas 中也同樣支援 DataTime 資料機制,可以藉助它實現許多有用的功能,例如 1,函式to_datetime() 將資料列表中的 Series 列轉化為 datetime 型別, ```python #Convert the type to datetime apple.Date = pd.to_datetime(apple.Date) apple['Date'].head() # 0 2014-07-08 1 2014-07-07 2 2014-07-03 3 2014-07-02 4 2014-07-01 Name: Date, dtype: datetime64[ns] ``` 2,DataFrame.resample(freq),將資料基於時間列以 freq 作為頻度對全域性資料做重取樣,計算出分段資料和、均值、方差等指標;下面例子中原資料的索引是 Datatime 資料格式,以月為時間單位求出各列資料的平均值 ```python # Resample the data based the offset,get the mean of data # BM — bussiness month end frequency apple_month = apple.resample("BM").mean() apple_month.head() ``` ![Snipaste_2020-07-26_23-30-33.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4sodze5cj30i106t74c.jpg) 下面將根據幾道練習題,簡單介紹一下 Pandas 是怎麼處理 DataFrame 資料的 #### 1 , to_datetime() 與 resample() 操作 **1.1,讀取資料** ```python 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 格式,需要格式處理一下 ![Snipaste_2020-07-26_23-37-50.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4sz6a656j30fi05qglm.jpg) **1.2,datetime 格式轉換** ```python #Convert the type to datetime apple.Date = pd.to_datetime(apple.Date) apple['Date'].head() ``` ![Snipaste_2020-07-26_23-46-23.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4t2s4w1fj30sr03xa9x.jpg) **1.3,將 Date 列設為 index ** ```python apple = apple.set_index("Date") # Set Index apple.head() ``` Date 雖然已經設為 index,但是時間排列卻並不清晰,datetime 資料可以直接排序這裡用 sort_index(ascending = True) 完成排序 ![Snipaste_2020-07-26_23-47-36.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4t41xsvaj30fk06r0sq.jpg) **1.4,對索引進行排序** ``` # Sort The DataFrame based on Date columns apple.sort_index(ascending = True).head() ``` ![Snipaste_2020-07-26_23-51-12.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4t7uivdij30ix061mx5.jpg) **1.5,以月為單位對資料取樣並獲取mean()** ```python # Resample the data based the offset,get the mean of data # BM — bussiness month end frequency apple_month = apple.resample("BM").mean() apple_month.head() ``` ![Snipaste_2020-07-26_23-53-05.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4t9rykmlj30jw06eglo.jpg) BM 全稱 Bussiness Month,是商業月的意思,在 Pandas 中稱為 DataOffset,除了月之外,還提供年、日、秒、小時、分..等作為取樣單位,當然也可以自定義 ![Snipaste_2020-07-27_00-10-00.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4trxly0cj30r70o3mzg.jpg) 關於 Data Offset 具體詳細內容可參考:https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases; **1.6,計算時間列表中最早日期與最晚日期相差天數** ```python (apple.index.max()-apple.index.min()).days # 12261 ``` #### 2,統計近兩年蘋果、特斯拉、IBM、LINKD各公司股價 **2.1,pandas_datareader 獲取資料** ```python import pandas as pd from pandas_datareader import data as web import datetime as dt start = 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 的用法) ![Snipaste_2020-07-27_00-30-57.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4udrfia3j30s30d5dg9.jpg) **2.2,獲取 股票 資料** ```python vol = df['Volume'] vol ``` ![Snipaste_2020-07-27_00-37-02.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4usll7i6j30fo05xdfu.jpg) **2.3,建立新列,表示 week、year ** 後面做聚類分析,聚類基準選擇的是 week、year , 因此需要提前建立好兩列(week,year)資料 ```python vol['week'] = vol.index.week vol['year'] = vol.index.year vol.head() ``` ![Snipaste_2020-07-27_00-40-59.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4uszu8d6j30fg06ajre.jpg) **2.4,groupby 聚類分組(先 week ,後 year)** ``` week = vol.groupby(['week','year']).sum() week.head() ``` 這樣就可以很清晰地比對,2019-2020年對於每一週來說各公司股票的總值變化啦 ![Snipaste_2020-07-27_00-46-45.png](http://ww1.sinaimg.cn/large/007wRTdIgy1gh4uthyejlj30fp06mjrc.jpg) 好了,以上就是本篇文章的所有內容啦;最後,感謝大家的閱讀! *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_Financi