使用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ì)算過程解釋:
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)谑褂眠^程中,結(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)文章
python3實(shí)現(xiàn)tailf命令的示例代碼
本文主要介紹了python3實(shí)現(xiàn)tailf命令的示例代碼,tail -f 是一個(gè)linux的操作命令.其主要的是會(huì)把文件里的最尾部的內(nèi)容顯顯示在屏幕上,并且不斷刷新,只要文件有變動(dòng)就可以看到最新的文件內(nèi)容,感興趣的可以了解一下2023-11-11pyside6-uic生成py代碼中文為unicode(亂碼)的問題解決方案
這篇文章主要介紹了如何解決pyside6-uic生成py代碼中文為unicode(亂碼)的問題,文中通過代碼和圖文介紹的非常詳細(xì),對(duì)大家解決問題有一定的幫助,需要的朋友可以參考下2024-02-02Python中多個(gè)數(shù)組行合并及列合并的方法總結(jié)
下面小編就為大家分享一篇Python中多個(gè)數(shù)組行合并及列合并的方法總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-04-04python urllib urlopen()對(duì)象方法/代理的補(bǔ)充說(shuō)明
這篇文章主要介紹了python urllib urlopen()對(duì)象方法/代理的補(bǔ)充說(shuō)明的相關(guān)資料,需要的朋友可以參考下2017-06-06深入探究Python中的多進(jìn)程模塊用法實(shí)例
多進(jìn)程是計(jì)算機(jī)編程中的一個(gè)概念,也可以說(shuō)是一種可用于實(shí)現(xiàn)并行性和利用多個(gè) CPU 內(nèi)核或處理器并發(fā)執(zhí)行任務(wù)的技術(shù),在本文中,我們將學(xué)習(xí)有關(guān) python 中多進(jìn)程處理的所有知識(shí)、理論和實(shí)際使用代碼2024-01-01使用Django和Flask獲取訪問來(lái)源referrer
這篇文章主要介紹了使用Django和Flask獲取訪問來(lái)源referrer,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2021-04-04