教你利用 Python 计算同比、环比、定基比

x33g5p2x  于2021-11-21 转载在 Python  
字(1.3k)|赞(0)|评价(0)|浏览(508)

1. 问题描述

日常处理销售相关的数据时,经常会遇到需要计算 同比、环比、定基比 的问题,计算方法是 「(当期 / 比较期 -1) * 100%」,在 Excel 中使用公式引用进行计算非常方便,其实使用 python 来做相应的计算也是非常简单的,本文就使用 python 来进行操作,计算出想要的结果。

先读取数据集,是 2019 年 1 月至 2021 年 3 月的销售数据。

import pandas as pd
import numpy as np
import time
import datetime

df_raw = pd.read_excel('./data.xlsx',sheet_name='Sheet1')
df_raw['日期'] = pd.to_datetime(df_raw['日期'])
df_raw = df_raw.set_index('日期')
df_raw

2. 解决方法

2.1 计算同比和环比

使用 pct_change() 函数,直接可以计算百分比对比(同比、环比)
df_raw['环比'] = df_raw['销售额'].pct_change(periods=1)
df_raw['同比'] = df_raw['销售额'].pct_change(periods=12)
df_raw['环比'] = df_raw['环比'].apply(lambda x:str(round(x * 100,2)) + '%').str.replace('nan%','')
df_raw['同比'] = df_raw['同比'].apply(lambda x:str(round(x * 100,2)) + '%').str.replace('nan%','')
df_raw

2.2 定基比

计算定基比(以 '2020-10-01' 为基准)
fixed_str = '2020-10-01'
# fixed_row = datetime.datetime.strptime(fixed_str, '%Y-%m-%d').date()
fixed_num = df_raw.loc[fixed_str,'销售额']
df_raw['定基比'] = df_raw['销售额'] / fixed_num - 1
df_raw['定基比'] = df_raw['定基比'].apply(lambda x:str(round(x * 100,2)) + '%').str.replace('nan%','')
df_raw

3. 总结

  • 使用 pandas 库 中的 pct_change() 函数 配合 periods 参数 可以方便地计算同比和环比。
  • 使用 apply 自定义函数计算出定基比。

4. 资料下载

我已将以上配套数据文件和代码文件打包上传至我的 Github 和 Gitee,感兴趣的读者可以下载学习和练手。

  • 「Github 项目地址」

「https://github.com/don2vito/wechat_project/tree/master/同比、环比、定基比」

  • 「Gitee 项目地址」

「https://gitee.com/don2vito/wechat_official_account/blob/master/023_《和时间做朋友》系列 /03. 同比、环比、定基比.ipynb」

欢迎关注

点分享

点收藏

点点赞

点在看

相关文章