使用pandas计算环比和同比的方法实例
作者:theskylife 时间:2021-02-15 18:06:34
前言
在进行业务数据分析时,往往需要使用pandas计算环比、同比及增长率等指标,为了能够更加方便的进行的统计数据,整理方法如下。
1.数据准备
为方便进行演示,此处提前生成需要进行统计的数据,数据已经是按照时间维度进行排序。
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.环比计算
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.同比计算
继续使用上述构建的数据源进行计算。
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()函数
pct_change主要涉及一下参数:
periods=1,用来设置计算的周期。
fill_method=‘pad’,如何在计算百分比变化之前处理缺失值(NA)。
limit=None,设置停止填充条件,即当遇到填充的连续缺失值的数量n时,停止此处填充
freq=None,从时间序列 API 中使用的增量(例如 ‘M’ 或 BDay())
4.1 使用例子1
#构建数据
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
数据展示:
计算环比:
#向下进行填充,当连续缺失值的数量大于2时不进行填充
test_df2['v'].pct_change(1,fill_method='ffill',limit=2)
计算效果图:
4.2 使用例子2
# 生成样本数据
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)})
样本数据截图:
计算同环比:
test_df3.pct_change(axis='columns',periods=-1)
计算效果截图:
4.3 使用例子3
#构建数据样本
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)
数据样本截图:
计算季度末环比:
test_df4["v"].pct_change(freq="Q")
计算效果图:
计算过程解释:
2020-03-31行处的值:使用3月份和1月份进行环比,即55.717305/84.492806-1
2020-06-30行处的值:使用6月份和3月份进行环比
计算环比增长
方法一:
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%') 小数格式化为百分数
方法二:
使用diff(periods=1, axis=0)) 一阶差分函数
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)
计算同比增长
使用一阶差分函数diff()
data['tongbi_shu'] = data.mony.diff(12)
data.fillna(0,inplace=True)
data['tongbi'] = data['tongbi_shu']/(data['mony'] - data['tongbi_shu'])
``
5.后记
来源:https://blog.csdn.net/qq_41780234/article/details/123383495
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 绘制酷炫的三维图步骤详解
![](https://img.aspxhome.com/file/2023/7/75217_0s.jpg)
python 利用文件锁单例执行脚本的方法
python基于opencv实现人脸识别
![](https://img.aspxhome.com/file/2023/8/68468_0s.jpg)
Yahoo!上的小秘密
![](https://img.aspxhome.com/file/UploadPic/20078/23/200782395619331s.jpg)
python3实现无权最短路径的方法
![](https://img.aspxhome.com/file/2023/2/76872_0s.png)
Python 操作 PostgreSQL 数据库示例【连接、增删改查等】
Django中ORM找出内容不为空的数据实例
pandas温差查询案例的实现
Python Cloudinary实现图像和视频上传详解
![](https://img.aspxhome.com/file/2023/2/88882_0s.png)
[关注细节的最佳方案]有效期时间格式的展现
![](https://img.aspxhome.com/file/UploadPic/200910/30/validity1-63s.gif)
Python3基础教程之递归函数简单示例
分类与类型的问题
![](https://img.aspxhome.com/file/UploadPic/20089/12/2008912131610841s.jpg)
python爬虫 正则表达式解析
PHP如何从txt文件中读取数据详解
![](https://img.aspxhome.com/file/2023/5/55725_0s.png)
php文件类型MIME对照表(比较全)
Python实现ATM系统
让数据站住脚-浅谈用户研究中的信度与效度
![](https://img.aspxhome.com/file/UploadPic/20109/10/banner21-91s.jpg)
深入理解Python3 内置函数大全
![](https://img.aspxhome.com/file/2023/1/87591_0s.png)
MySQL高级查询方法之记录查询
js游戏 俄罗斯方块 源代码
![](https://img.aspxhome.com/file/UploadPic/20081/24/200812414337986s.jpg)