Datatime 是 Python 中一種時間數據類型,對於不同時間格式之間的轉換是比較方便的,而在 Pandas 中也同樣支持 DataTime 數據機制,可以借助它實現許多有用的功能,例如
1,函數to_datetime() 將數據列表中的 Series 列轉化為 datetime 類型,
#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 數據格式,以月為時間單位求出各列數據的平均值
# 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()
下面將根據幾道練習題,簡單介紹一下 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 datetime
apple.Date = pd.to_datetime(apple.Date)
apple['Date'].head()
**1.3,將 Date 列設為 index **
apple = apple.set_index("Date")
# Set Index
apple.head()
Date 雖然已經設為 index,但是時間排列卻並不清晰,datetime 數據可以直接排序這里用 sort_index(ascending = True) 完成排序
1.4,對索引進行排序
# Sort The DataFrame based on Date columns
apple.sort_index(ascending = True).head()
1.5,以月為單位對數據采樣並獲取mean()
# 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()
BM 全稱 Bussiness Month,是商業月的意思,在 Pandas 中稱為 DataOffset,除了月之外,還提供年、日、秒、小時、分..等作為采樣單位,當然也可以自定義
關於 Data Offset 具體詳細內容可參考:https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases;
1.6,計算時間列表中最早日期與最晚日期相差天數
(apple.index.max()-apple.index.min()).days
#
12261
2,統計近兩年蘋果、特斯拉、IBM、LINKD各公司股價
2.1,pandas_datareader 獲取數據
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 的用法)
2.2,獲取 股票 數據
vol = df['Volume']
vol
**2.3,創建新列,表示 week、year **
后面做聚類分析,聚類基准選擇的是 week、year , 因此需要提前創建好兩列(week,year)數據
vol['week'] = vol.index.week
vol['year'] = vol.index.year
vol.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