数据对比环比同比
Python数据分析入门Python
问题
如何计算环比和同比增长率?
答题要点
import pandas as pd
df = pd.read_csv('monthly_data.csv')
df['month'] = pd.to_datetime(df['month'])
df = df.sort_values('month')
# 环比增长率(Month-over-Month)
df['mom_growth'] = df['revenue'].pct_change() * 100
df['mom_diff'] = df['revenue'].diff()
# 同比增长率(Year-over-Year)
df['yoy_growth'] = df['revenue'].pct_change(periods=12) * 100
df['yoy_diff'] = df['revenue'].diff(periods=12)
# 格式化显示
df['mom_growth_str'] = df['mom_growth'].apply(lambda x: f'{x:+.1f}%' if pd.notna(x) else '-')
df['yoy_growth_str'] = df['yoy_growth'].apply(lambda x: f'{x:+.1f}%' if pd.notna(x) else '-')
print(df[['month', 'revenue', 'mom_growth_str', 'yoy_growth_str']])
# 可视化对比
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(12, 6))
ax1.plot(df['month'], df['revenue'], marker='o', label='收入', color='blue')
ax1.set_ylabel('收入', color='blue')
ax2 = ax1.twinx()
ax2.plot(df['month'], df['mom_growth'], marker='s', label='环比增长率', color='red', linestyle='--')
ax2.plot(df['month'], df['yoy_growth'], marker='^', label='同比增长率', color='green', linestyle='--')
ax2.set_ylabel('增长率 (%)')
ax2.axhline(0, color='gray', linestyle=':')
plt.title('收入及增长率趋势')
fig.legend(loc='upper left', bbox_to_anchor=(0.1, 0.9))
plt.show()
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题