Python數(shù)據(jù)分析工具:Pandas_Part 2

序言:

????今天不截圖,嘗試下純代碼編輯效果會(huì)不會(huì)看起來舒服一些


【課程2.7】 時(shí)間模塊:datetime

????datetime模塊,主要掌握:datetime.date(), datetime.datetime(), datetime.timedelta()
????日期解析方法:parser.parse

datetime.date:date對(duì)象
import datetime # 也可以寫 from datetime import date

today = datetime.date.today()
print(today, type(today))
print(str(today), type(str(today)))
# datetime.date.today 返回今日
# 輸出格式為 date類

t = datetime.date(2016, 6, 1)
print(t)
# (年,月,日) -> 直接得到當(dāng)時(shí)日期
datetime.datetime: datetime 對(duì)象
now = datetime.datetime.now()
print(now, type(now))
print(str(now), type(str(now)))
# .now()方法,輸出當(dāng)前時(shí)間
# 輸出格式為 datetime類
# 可通過str()轉(zhuǎn)化為字符串

t1 = datetime.datetime(2016,6,1)
t2 = datetime.datetime(2014,1,1,12,44,33)
print(t1, t2)
# (年,月,日,時(shí),分,秒),至少輸入年月日

t2 - t1
# 相減得到時(shí)間差   —— timedelta
parser.parse:日期字符串轉(zhuǎn)換
from dateutil.parser import parse

date = "13-03-2018"
t = parse(date)
print(t, type(t))
# 直接將str轉(zhuǎn)化成datetime.datetime

print(parse("2000-1-1"), "\n",
     parse("5/1/2014"), "\n",
     parse("5/1/2014", dayfirst = True), "\n", # 國際通用格式中,月/日/年,可以通過dayfirst來設(shè)置
     parse("22/1/2014"), "\n",
     parse("Jan 31, 1997 10:45 PM")) 
# 各種格式可以解析,但無法支持中文


【課程2.8】 Pandas時(shí)刻數(shù)據(jù):Timestamp

????時(shí)刻數(shù)據(jù)代表時(shí)間點(diǎn),是pandas的數(shù)據(jù)類型,是將值與時(shí)間點(diǎn)相關(guān)聯(lián)的最基本類型的時(shí)間序列數(shù)據(jù)
????pandas.Timestamp()

pd.Timestamp()
import numpy as np
import pandas as pd


date1 = datetime.datetime(2016,12,1,12,45,30) # 創(chuàng)建一個(gè)datetime.datetime
date2 = "2017-12-21" # 創(chuàng)建一個(gè)字符串
t1 = pd.Timestamp(date1)
t2 = pd.Timestamp(date2)
print(t1, type(t1))
print(t2, type(t2))
print(pd.Timestamp("2017-12-21 15:00:22"))
# 直接生成pandas的時(shí)刻數(shù)據(jù) -> 時(shí)間戳
# 數(shù)據(jù)類型為 pandas的Timestamp
pd.to_datetime
from datetime import datetime

date1 = datetime(2016,12,1,12,45,30)
date2 = "2018-03-14"
t1 = pd.to_datetime(date1)
t2 = pd.to_datetime(date2)
print(t1, type(t1))
print(t2, type(t2))
# pd.to_datetime():如果是單個(gè)時(shí)間數(shù)據(jù),轉(zhuǎn)換成pandas的時(shí)刻數(shù)據(jù),數(shù)據(jù)類型為Timestamp

lst_date = ['2017-12-21', '2017-12-22', '2017-12-23']
t3 = pd.to_datetime(lst_date)
print(t3, type(t3))
# 多個(gè)時(shí)間數(shù)據(jù),將會(huì)轉(zhuǎn)換為pandas的DatetimeIndex
pd.to_datetime -> 多個(gè)時(shí)間數(shù)據(jù)轉(zhuǎn)換時(shí)間戳索引

date1 = [datetime(2015,6,1),datetime(2015,7,1),datetime(2015,8,1),datetime(2015,9,1),datetime(2015,10,1)]
date2 = ['2018-2-1','2018-2-2','2018-2-3','2018-2-4','2018-2-5','2018-2-6']
print(date1)
print(date2)
t1 = pd.to_datetime(date1)
t2 = pd.to_datetime(date2)
print(t1)
print(t2)
# 多個(gè)時(shí)間數(shù)據(jù)轉(zhuǎn)換為 DatetimeIndex

date3 = ['2018-2-1','2018-2-2','2018-2-3', 'hello world!', '2018-2-4','2018-2-5','2018-2-6']
t3 = pd.to_datetime(date3, errors = "ignore")
print(t3, type(t3))
# 當(dāng)一組時(shí)間序列中夾雜其他格式數(shù)據(jù),可用errors參數(shù)返回
# errors = "ignore": 不可解析時(shí)返回原始輸入,這里就是直接生成一般數(shù)組

t4 = pd.to_datetime(date3, errors = "coerce")
print(t4, type(t4))
# errors = 'coerce':不可擴(kuò)展,缺失值返回NaT(Not a Time),結(jié)果認(rèn)為DatetimeIndex


【課程2.9】 Pandas時(shí)間戳索引:DatetimeIndex

????核心:pd.date_range()

pd.DatetimeIndex()與TimeSeries時(shí)間序列

rng = pd.DatetimeIndex(['2018-2-1','2018-2-2','2018-2-3', '2018-2-4', "2018-2-5"])
print(rng, type(rng))
print(rng[0], type(rng[0]))
# 直接生成時(shí)間戳索引,支持str、datetime.datetime
# 單個(gè)時(shí)間戳為Timestamp,多個(gè)時(shí)間戳為DatetimeIndex

st = pd.Series(np.random.rand(len(rng)), index = rng)
print(st, type(st))
print(st.index)
# 以DatetimeIndex為index的Series,為TimeSeries,時(shí)間序列

pd.date_range()-日期范圍:生成日期范圍
2種生成方式:①start + end; ②start/end + periods
默認(rèn)頻率:day

rng1 = pd.date_range("1/1/2017", "1/10/2017", normalize = True)
rng2 = pd.date_range(start = "1/1/2017", periods = 10)
rng3 = pd.date_range(end = "1/30/2017 15:00:00", periods = 10) # 增加了時(shí)、分、秒
print(rng1, type(rng1))
print(rng2)
print(rng3)
print("-------------")
# 直接生成DatetimeIndex
# pd.date_range((start=None, end=None, periods=None, freq='D', tz=None, normalize=False, name=None, closed=None, **kwargs)
# start:開始時(shí)間
# end:結(jié)束時(shí)間
# periods:偏移量
# freq:頻率,默認(rèn)天,pd.date_range()默認(rèn)頻率為日歷日,pd.bdate_range()默認(rèn)頻率為工作日
# tz:時(shí)區(qū)

rng4 = pd.date_range(start = "1/1/2017 15:30", periods = 10, name = "hello world!", normalize = True)
print(rng4)
print("----------------")
# normalize:時(shí)間參數(shù)值正則化到午夜時(shí)間戳(這里最后就直接變成0:00:00,并不是15:30:00)
# name:索引對(duì)象名稱

print(pd.date_range("20170101", "20170104")) # 20170101也可讀取
print(pd.date_range("20170101", "20170104", closed = "right")) # 左開右閉
print(pd.date_range("20170101", "20170104", closed = "left")) # 左閉右開
print("----------------")
# closed:默認(rèn)為None的情況下,左閉右閉,left則左閉右開,right則左開右閉

print(pd.bdate_range("20170101", "20170107"))
# pd.bdate_range()默認(rèn)頻率為工作日

print(list(pd.date_range(start = "1/1/2017", periods = 10)))
# 直接轉(zhuǎn)化為list,元素為Timestamp


pd.date_range()-日期范圍:頻率(1)

print(pd.date_range("2017/1/1", "2017/1/4")) # 默認(rèn)freq = "D":每日歷日
print(pd.date_range("2017/1/1", "2017/1/4", freq = "B")) # B:每工作日
print(pd.date_range("2017/1/1", "2017/1/2", freq = "H")) # H:每小時(shí)
print(pd.date_range("2017/1/1 12:00", "2017/1/1 12:10", freq = "T")) # T/MIN:每分
print(pd.date_range("2017/1/1 12:00", "2017/1/1 12:00:10", freq = "S")) # S:每秒
print(pd.date_range("2017/1/1 12:00", "2017/1/1 12:00:10", freq = "L")) # L:每毫秒(千分之一秒)
print(pd.date_range("2017/1/1 12:00", "2017/1/1 12:00:10", freq = "U")) # L:每微秒(百萬分之一秒)

print(pd.date_range("2017/1/1", "2017/2/1", freq = "W-MON"))
# W-MON:從指定星期幾開始算起,每周
# 星期幾縮寫:MON/TUE/WED/THU/FRI/SAT/SUN

print(pd.date_range("2017/1/1", "2017/5/1", freq = "WOM-2MON"))
#  WOM-2MON:每月的第幾個(gè)星期幾開始算,這里是每月第二個(gè)星期一

pd.date_range()-日期范圍:頻率(2)

print(pd.date_range("2017", "2018", freq = "M"))
print(pd.date_range("2017", "2020", freq = "Q-DEC"))
print(pd.date_range("2017", "2020", freq = "A-DEC"))
print("-----------")
# M:每月最后一個(gè)日歷日
# Q-月:指定月為季度末,每個(gè)季度末最后一月的最后一個(gè)日歷日
# A-月:每年指定月份的最后一個(gè)日歷日
# 月縮寫:JAN/FEB/MAR/APR/MAY/JUN/JUL/AUG/SEP/OCT/NOV/DEC
# 所以Q-月只有三種情況:1-4-7-10,2-5-8-11,3-6-9-12

print(pd.date_range("2017", "2018", freq = "BM"))
print(pd.date_range("2017", "2020", freq = "BQ-DEC"))
print(pd.date_range("2017", "2020", freq = "BA-DEC"))
print("-----------")
# BM:每月最后一個(gè)工作日
# BQ-月:指定月為季度末,每個(gè)季度末最后一月的最后一個(gè)工作日
# BA-月:每年指定月份的最后一個(gè)工作日

print(pd.date_range("2017", "2018", freq = "MS"))
print(pd.date_range("2017", "2020", freq = "QS-DEC"))
print(pd.date_range("2017", "2020", freq = "AS-DEC"))
print('------')
# M:每月第一個(gè)日歷日
# Q-月:指定月為季度末,每個(gè)季度末最后一月的第一個(gè)日歷日
# A-月:每年指定月份的第一個(gè)日歷日

print(pd.date_range('2017','2018', freq = 'BMS'))  
print(pd.date_range('2017','2020', freq = 'BQS-DEC'))  
print(pd.date_range('2017','2020', freq = 'BAS-DEC')) 
print('------')
# BM:每月第一個(gè)工作日
# BQ-月:指定月為季度末,每個(gè)季度末最后一月的第一個(gè)工作日
# BA-月:每年指定月份的第一個(gè)工作日

pd.date_range()-日期范圍:復(fù)合頻率
print(pd.date_range('2017/1/1', '2017/2/1', freq = '7D'))  # 7天
print(pd.date_range("2017/1/1", "2017/1/2", freq = "2H30MIN")) # 2小時(shí)30分鐘
print(pd.date_range('2017','2018', freq = '2M'))  # 2月,每月最后一個(gè)日歷日

asfreq:時(shí)期頻率轉(zhuǎn)換


ts = pd.Series(np.random.rand(4), 
              index = pd.date_range("20170101", "20170104"))
print(ts)
print(ts.asfreq("4H", method = "ffill"))
# 改變頻率,這里是D改為4H
# method:插值模式,None不插值,ffill用之前值填充,bfill用之后值填充

pd.date_range()-日期范圍:超前/滯后數(shù)據(jù)

ts = pd.Series(np.random.rand(4),
              index = pd.date_range("20170101", "20170104"))
print(ts)

print(ts.shift(2))
print(ts.shift(-2))
# 正數(shù):數(shù)值后移(滯后);負(fù)數(shù):數(shù)值前移(超前)

per = ts/ts.shift(1) - 1
print(per)
print("------------")
# 計(jì)算變化百分比,這里計(jì)算:該時(shí)間戳與上一個(gè)時(shí)間戳相比,變化百分

print(ts.shift(2, freq = "D"))
print(ts.shift(2, freq = "T"))
# 加上freq參數(shù):對(duì)時(shí)間戳進(jìn)行位移,而不是對(duì)數(shù)值進(jìn)行位移


【課程2.10】 Pandas時(shí)期:Period

????核心:pd.Period()

pd.Period()創(chuàng)建時(shí)期
p = pd.Period("2017", freq = "M")
print(p, type(p))
# 生成一個(gè)以2017-01開始,月為頻率的時(shí)間構(gòu)造器
# pd.Period()參數(shù):一個(gè)時(shí)間戳 + freq 參數(shù) -> freq 用于指明該 period 的長度,時(shí)間戳則說明該 period在時(shí)間軸上的位置


print(p + 1)
print(p - 2)
print(pd.Period("2012", freq = "A-DEC") -1)
# 通過加減整數(shù),將周期整體移動(dòng)
# 這里按照 月、年 移動(dòng)
# Period('2012', freq = 'A-DEC')可以看成多個(gè)時(shí)間期的時(shí)間段中的游標(biāo)
pd.period_range()創(chuàng)建時(shí)期范圍
prng = pd.period_range("1/1/2011", "1/1/2012", freq = "M")
print(prng, type(prng))
print(prng[0], type(prng[0]))
# 數(shù)據(jù)格式為PeriodIndex,單個(gè)數(shù)值為Period

ts = pd.Series(np.random.rand(len(prng)), index = prng)
print(ts, type(ts))
print(ts.index)
# 時(shí)間序列

# Timestamp表示一個(gè)時(shí)間戳,是一個(gè)時(shí)間截面;Period是一個(gè)時(shí)期,是一個(gè)時(shí)間段?。〉珒烧咦鳛閕ndex時(shí)區(qū)別不大
asfreq:頻率轉(zhuǎn)換
p = pd.Period("2017", "A-DEC")
print(p)
print(p.asfreq("M", how = "start")) # 也可寫 how = "s"
print(p.asfreq("D", how = "end"))   # 也可寫 how = "e"
# 通過.asfreq(freq, method = None, how = None)方法轉(zhuǎn)換成別的頻率

prng = pd.period_range("2017", "2018", freq = "M")
ts1 = pd.Series(np.random.rand(len(prng)), index = prng)
ts2 = pd.Series(np.random.rand(len(prng)), index = prng.asfreq("D", how = "start"))
print(ts1.head(), len(ts1))
print(ts2.head(), len(ts2))
# asfreq也可以轉(zhuǎn)換TIMESeries的index
時(shí)間戳與時(shí)期之間的轉(zhuǎn)換:pd.to_period()、pd.to_timestamp()
rng = pd.date_range("2017/1/1", periods = 10, freq = "M")
prng = pd.period_range("2017", "2018", freq = "M")

ts1 = pd.Series(np.random.rand(len(rng)), index = rng)
print(ts1.head())
print(ts1.to_period().head())
# 每月最后一日,轉(zhuǎn)化為每月

ts2 = pd.Series(np.random.rand(len(prng)), index = prng)
print(ts2.head())
print(ts2.to_timestamp().head())
# 每月,轉(zhuǎn)化為每月第一天


【課程2.11】 時(shí)間序列 - 索引及切片

????TimeSeries是Series的一個(gè)子類,所以Series索引及數(shù)據(jù)選取方面的方法基本一樣
????同時(shí)TimeSeries通過時(shí)間序列有更便捷的方法做索引和切片

索引
from datetime import datetime

rng = pd.date_range("2017/1", "2017/3")
ts = pd.Series(np.random.rand(len(rng)), index = rng)
print(ts.head())

print(ts[0])
print(ts[:2])
print("--------")
# 基本下標(biāo)位置索引

print(ts["2017/1/2"])
print(ts["20170103"])
print(ts["1/10/2017"])
print(ts[datetime(2017,1,20)])
print("---------")
# 時(shí)間序列標(biāo)簽索引,支持各種時(shí)間字符串,以及datetime.datetime

# 時(shí)間序列由于按照時(shí)間先后排序,故不用考慮順序問題
# 索引方法同樣適用于Dataframe
切片
rng = pd.date_range("2017/1", "2017/3", freq = "12H")
ts = pd.Series(np.random.rand(len(rng)), index = rng)

print(ts["2017/1/5": "2017/1/10"])
print("---------")
# 和Series按照index索引原理一樣,也是末端包含

print(ts["2017/2"].head())
# 傳入月,直接得到一個(gè)切片
重復(fù)索引的時(shí)間序列
dates = pd.DatetimeIndex(['1/1/2015','1/2/2015','1/3/2015','1/4/2015','1/1/2015','1/2/2015'])
ts = pd.Series(np.random.rand(len(dates)), index = dates)
print(ts)
print(ts.is_unique, ts.index.is_unique)
print("-------")
# index有重復(fù),is_unique檢查 → values唯一,index不唯一

print(ts["20150101"], type(ts["20150101"]))
print(ts["20150104"], type(ts["20150104"]))
print("-------")
# index有重復(fù)的將返回多個(gè)值

print(ts.groupby(level = 0).mean())
# 通過groupby做分組,重復(fù)的值這里用平均值處理


【課程2.12】 時(shí)間序列 - 重采樣

????將時(shí)間序列從一個(gè)頻率轉(zhuǎn)換為另一個(gè)頻率的過程,且會(huì)有數(shù)據(jù)的結(jié)合
????降采樣:高頻數(shù)據(jù) → 低頻數(shù)據(jù),eg.以天為頻率的數(shù)據(jù)轉(zhuǎn)為以月為頻率的數(shù)據(jù)
????升采樣:低頻數(shù)據(jù) → 高頻數(shù)據(jù),eg.以年為頻率的數(shù)據(jù)轉(zhuǎn)為以月為頻率的數(shù)據(jù)

重采樣:.resample()
創(chuàng)建一個(gè)以天為頻率的TimeSeries,重采樣為按2天為頻率
rng = pd.date_range("20170101", periods = 12)
ts = pd.Series(np.arange(len(rng)), index = rng)
print(ts)
print("\n")

ts_re = ts.resample("5D")
ts_re2 = ts.resample("5D").sum()
print(ts_re, type(ts_re))
print("\n")
print(ts_re2, type(ts_re2))
print("---------")
# ts.resample("5D"):得到一個(gè)重采樣構(gòu)建器,頻率改為5天
# ts.resample("5d").sum():得到一個(gè)新的聚合后的Series,聚合方式為求和
# freq:重采樣頻率 -> ts.resample("5D")
# .sum():聚合方法

print(ts.resample('5D').mean(),'→ 求平均值\n')
print(ts.resample('5D').max(),'→ 求最大值\n')
print(ts.resample('5D').min(),'→ 求最小值\n')
print(ts.resample('5D').median(),'→ 求中值\n')
print(ts.resample('5D').first(),'→ 返回第一個(gè)值\n')
print(ts.resample('5D').last(),'→ 返回最后一個(gè)值\n')
print(ts.resample('5D').ohlc(),'→ OHLC重采樣\n')
# OHLC:金融領(lǐng)域的時(shí)間序列聚合方式 → open開盤、high最大值、low最小值、close收盤
降采樣
rng = pd.date_range("20170101", periods = 12)
ts = pd.Series(np.arange(1,13), index = rng)
print(ts)
print("-------")
print(ts.resample("5D").sum(),'→ 默認(rèn)\n')
print(ts.resample('5D', closed = 'left').sum(),'→ left\n')
print(ts.resample('5D', closed = 'right').sum(),'→ right\n')
print('-----')
# closed:各時(shí)間段哪一端是閉合(即包含)的,默認(rèn) 左閉右閉
# 詳解:這里values為0-11,按照5D重采樣 → [1,2,3,4,5],[6,7,8,9,10],[11,12]
# left指定間隔左邊為結(jié)束 → [1,2,3,4,5],[6,7,8,9,10],[11,12]
# right指定間隔右邊為結(jié)束 → [1],[2,3,4,5,6],[7,8,9,10,11],[12]

print(ts.resample('5D', label = 'left').sum(),'→ leftlabel\n')
print(ts.resample('5D', label = 'right').sum(),'→ rightlabel\n')
# label:聚合值的index,默認(rèn)為取左
# 值采樣認(rèn)為默認(rèn)(這里closed默認(rèn))
升采樣及插值
rng = pd.date_range('2017/1/1 0:0:0', periods = 5, freq = 'H')
ts = pd.DataFrame(np.arange(15).reshape(5,3),
                  index = rng,
                  columns = ['a','b','c'])
print(ts)

print(ts.resample('15T').asfreq())
print(ts.resample('15T').ffill())
print(ts.resample('15T').bfill())
# 低頻轉(zhuǎn)高頻,主要是如何插值
# .asfreq():不做填充,返回Nan
# .ffill():向上填充
# .bfill():向下填充
時(shí)期重采樣 - Period
prng = pd.period_range('2016','2017',freq = 'M')
ts = pd.Series(np.arange(len(prng)), index = prng)
print(ts)

print(ts.resample('3M').sum())  # 降采樣
print(ts.resample('15D').ffill())  # 升采樣
最后:

Pandas課程作業(yè)
Pandas課程作業(yè)答案
以上完整代碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容