使用pandas計算環(huán)比和同比的方法實例
前言
在進行業(yè)務數(shù)據(jù)分析時,往往需要使用pandas計算環(huán)比、同比及增長率等指標,為了能夠更加方便的進行的統(tǒng)計數(shù)據(jù),整理方法如下。
1.數(shù)據(jù)準備
為方便進行演示,此處提前生成需要進行統(tǒng)計的數(shù)據(jù),數(shù)據(jù)已經(jīng)是按照時間維度進行排序。
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)比計算
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.同比計算
繼續(xù)使用上述構建的數(shù)據(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.關于pct_change()函數(shù)
pct_change主要涉及一下參數(shù):
- periods=1,用來設置計算的周期。
- fill_method=‘pad’,如何在計算百分比變化之前處理缺失值(NA)。
- limit=None,設置停止填充條件,即當遇到填充的連續(xù)缺失值的數(shù)量n時,停止此處填充
- freq=None,從時間序列 API 中使用的增量(例如 ‘M’ 或 BDay())
4.1 使用例子1
#構建數(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ù)展示:
計算環(huán)比:
#向下進行填充,當連續(xù)缺失值的數(shù)量大于2時不進行填充 test_df2['v'].pct_change(1,fill_method='ffill',limit=2)
計算效果圖:
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ù)截圖:
計算同環(huán)比:
test_df3.pct_change(axis='columns',periods=-1)
計算效果截圖:
4.3 使用例子3
#構建數(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ù)樣本截圖:
計算季度末環(huán)比:
test_df4["v"].pct_change(freq="Q")
計算效果圖:
計算過程解釋:
2020-03-31行處的值:使用3月份和1月份進行環(huán)比,即55.717305/84.492806-1
2020-06-30行處的值:使用6月份和3月份進行環(huán)比
計算環(huán)比增長
方法一:
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ù)格式化為百分數(shù)
方法二:
使用diff(periods=1, axis=0)) 一階差分函數(shù)
periods:移動的幅度 默認值為1
axis:移動的方向,{0 or ‘index’, 1 or ‘columns’},如果為0或者’index’,則上下移動,如果為1或者’columns’,則左右移動。默認列向移動
data['huanbi_1'] = data.mony.diff()
方法三:
使用pct_change()
data['huanbi_1'] = data.mony.pct_change() data.fillna(0,inplace=True)
計算同比增長
使用一階差分函數(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.后記
以上就是時候用pandas進行計算同比和環(huán)比的方法,請在使用過程中,結合數(shù)據(jù)情況先進行數(shù)據(jù)清洗后,再選擇合適的方法進行計算。
到此這篇關于使用pandas計算環(huán)比和同比的文章就介紹到這了,更多相關pandas計算環(huán)比和同比內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pyside6-uic生成py代碼中文為unicode(亂碼)的問題解決方案
這篇文章主要介紹了如何解決pyside6-uic生成py代碼中文為unicode(亂碼)的問題,文中通過代碼和圖文介紹的非常詳細,對大家解決問題有一定的幫助,需要的朋友可以參考下2024-02-02python urllib urlopen()對象方法/代理的補充說明
這篇文章主要介紹了python urllib urlopen()對象方法/代理的補充說明的相關資料,需要的朋友可以參考下2017-06-06