使用pandas計(jì)算環(huán)比和同比的方法實(shí)例
前言
在進(jìn)行業(yè)務(wù)數(shù)據(jù)分析時(shí),往往需要使用pandas計(jì)算環(huán)比、同比及增長(zhǎng)率等指標(biāo),為了能夠更加方便的進(jìn)行的統(tǒng)計(jì)數(shù)據(jù),整理方法如下。
1.數(shù)據(jù)準(zhǔn)備
為方便進(jìn)行演示,此處提前生成需要進(jìn)行統(tǒng)計(jì)的數(shù)據(jù),數(shù)據(jù)已經(jīng)是按照時(shí)間維度進(jìn)行排序。
months = pd.date_range(start='2010-01-01', end='2020-12-31', freq='M')
test_df = pd.DataFrame({'month': months,
'v': 100*np.random.rand(months.shape[0], 1).reshape(months.shape[0])})
2.環(huán)比計(jì)算
2.1 方法1
test_df['v_last']=test_df['v'].shift(1) test_df['month_erlier_1']=test_df['v']/test_df['v_last']-1
2.2 方法2
test_df['m_m_diff']=test_df['v'].diff() test_df['month_erlier_2']=test_df['m_m_diff']/test_df['v'].shift(1)
2.3 方法3
test_df['month_erlier_3']=test_df['v'].pct_change()
3.同比計(jì)算
繼續(xù)使用上述構(gòu)建的數(shù)據(jù)源進(jìn)行計(jì)算。
3.1 方法1
test_df["last_year_v"]=test_df['v'].shift(12) test_df['year_erlier_1']=test_df['v']/test_df['last_year_v']-12
3.2 方法2
test_df["year_diff"]=test_df['v'].diff(12) test_df['year_diff'].fillna(0,inplace=True) test_df['year_erlier_2']=test_df['year_diff']/(test_df['v']-test_df['year_diff'])
3.3 方法3
test_df['year_erlier_3']=test_df["v"].pct_change(periods=12)
4.關(guān)于pct_change()函數(shù)
pct_change主要涉及一下參數(shù):
- periods=1,用來(lái)設(shè)置計(jì)算的周期。
- fill_method=‘pad’,如何在計(jì)算百分比變化之前處理缺失值(NA)。
- limit=None,設(shè)置停止填充條件,即當(dāng)遇到填充的連續(xù)缺失值的數(shù)量n時(shí),停止此處填充
- freq=None,從時(shí)間序列 API 中使用的增量(例如 ‘M’ 或 BDay())
4.1 使用例子1
#構(gòu)建數(shù)據(jù)
months = pd.date_range(start='2020-01-01', end='2020-12-31', freq='M')
test_df2 = pd.DataFrame({'month': months,
'v': 100*np.random.rand(months.shape[0], 1).reshape(months.shape[0])})
test_df2.loc[((test_df2.index>5) & (test_df2.index<9) ),'v']=np.nan
test_df2.loc[test_df2.index==3,'v']=np.nan
test_df2.loc[test_df2.index==10,'v']=np.nan
數(shù)據(jù)展示:

計(jì)算環(huán)比:
#向下進(jìn)行填充,當(dāng)連續(xù)缺失值的數(shù)量大于2時(shí)不進(jìn)行填充 test_df2['v'].pct_change(1,fill_method='ffill',limit=2)
計(jì)算效果圖:

4.2 使用例子2
# 生成樣本數(shù)據(jù)
test_df3 = pd.DataFrame({'2020': 100*np.random.rand(5).reshape(5),
'2019': 100*np.random.rand(5).reshape(5),
'2018': 100*np.random.rand(5).reshape(5)})
樣本數(shù)據(jù)截圖:

計(jì)算同環(huán)比:
test_df3.pct_change(axis='columns',periods=-1)
計(jì)算效果截圖:

4.3 使用例子3
#構(gòu)建數(shù)據(jù)樣本
months = pd.date_range(start='2020-01-01', end='2020-12-31', freq='M')
test_df4 = pd.DataFrame({
'v': 100*np.random.rand(months.shape[0], 1).reshape(months.shape[0])}, index=months)
數(shù)據(jù)樣本截圖:

計(jì)算季度末環(huán)比:
test_df4["v"].pct_change(freq="Q")
計(jì)算效果圖:

計(jì)算過(guò)程解釋:
2020-03-31行處的值:使用3月份和1月份進(jìn)行環(huán)比,即55.717305/84.492806-1
2020-06-30行處的值:使用6月份和3月份進(jìn)行環(huán)比
計(jì)算環(huán)比增長(zhǎng)
方法一:
for i in range(0,len(data)):
if i == 0:
data['huanbi'][i] = 'null'
else:
data['huanbi'][i] = format((data['mony'][i] - data['mony'][i-1])/data['mony'][i-1],'.2%')
#format(res,'.2%') 小數(shù)格式化為百分?jǐn)?shù)
方法二:
使用diff(periods=1, axis=0)) 一階差分函數(shù)
periods:移動(dòng)的幅度 默認(rèn)值為1
axis:移動(dòng)的方向,{0 or ‘index’, 1 or ‘columns’},如果為0或者’index’,則上下移動(dòng),如果為1或者’columns’,則左右移動(dòng)。默認(rèn)列向移動(dòng)
data['huanbi_1'] = data.mony.diff()
方法三:
使用pct_change()
data['huanbi_1'] = data.mony.pct_change() data.fillna(0,inplace=True)
計(jì)算同比增長(zhǎng)
使用一階差分函數(shù)diff()
data['tongbi_shu'] = data.mony.diff(12) data.fillna(0,inplace=True) data['tongbi'] = data['tongbi_shu']/(data['mony'] - data['tongbi_shu']) ``
5.后記
以上就是時(shí)候用pandas進(jìn)行計(jì)算同比和環(huán)比的方法,請(qǐng)?jiān)谑褂眠^(guò)程中,結(jié)合數(shù)據(jù)情況先進(jìn)行數(shù)據(jù)清洗后,再選擇合適的方法進(jìn)行計(jì)算。
到此這篇關(guān)于使用pandas計(jì)算環(huán)比和同比的文章就介紹到這了,更多相關(guān)pandas計(jì)算環(huán)比和同比內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python logging 重復(fù)寫(xiě)日志問(wèn)題解決辦法詳解
這篇文章主要介紹了python logging 重復(fù)寫(xiě)日志問(wèn)題解決辦法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
使用python的turtle繪畫(huà)滑稽臉實(shí)例
今天小編就為大家分享一篇使用python的turtle繪畫(huà)滑稽臉實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
python實(shí)現(xiàn)跨年煙花動(dòng)態(tài)效果
這篇文章主要介紹了python實(shí)現(xiàn)跨年煙花的動(dòng)態(tài)效果,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2023-01-01
PyTorch中torch.save()的用法和應(yīng)用小結(jié)
本文主要介紹了PyTorch中torch.save()的用法和應(yīng)用小結(jié),torch.save()的主要作用就是將PyTorch對(duì)象保存到磁盤(pán)上,下面就來(lái)具體介紹一下,感興趣的可以了解一下2024-03-03
Python函數(shù)中的不定長(zhǎng)參數(shù)相關(guān)知識(shí)總結(jié)
今天給大家?guī)?lái)的是關(guān)于Python函數(shù)的相關(guān)知識(shí),文章圍繞著Python不定長(zhǎng)參數(shù)展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
簡(jiǎn)單介紹Python中的幾種數(shù)據(jù)類(lèi)型
Python基本內(nèi)置數(shù)據(jù)類(lèi)型有很多種,比如:整型(數(shù)字)、字符串、元組、列表、字典和布爾類(lèi)型,下面就來(lái)給大家詳細(xì)介紹下2016-01-01
tensorflow 輸出權(quán)重到csv或txt的實(shí)例
今天小編就為大家分享一篇tensorflow 輸出權(quán)重到csv或txt的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
關(guān)于VSCode?配置使用?PyLint?語(yǔ)法檢查器的問(wèn)題
這篇文章主要介紹了VSCode?配置使用?PyLint?語(yǔ)法檢查器,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06

