You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计多年度雅虎金融数据集各月份的平均百分比涨跌幅

实现步骤

首先确保你的Date索引为datetime类型,未转换的话先执行类型转换:

import pandas as pd
df.index = pd.to_datetime(df.index)

之后按月份字段分组计算平均涨跌幅,直接匹配你需要的输出格式:

# 按月份分组求平均,保留2位小数
result = df.groupby(df.index.month)['Adj Close'].mean().round(2).reset_index()
# 重命名列符合要求
result.columns = ['Month (int)', 'Adj Close (%)']
# 生成YYYYMMDD格式的Date索引
result['Date'] = [pd.to_datetime(f'2000-{m:02d}-01').strftime('%Y%m%d') for m in result['Month (int)']]
result = result.set_index('Date')
# 调整列顺序
result = result[['Adj Close (%)', 'Month (int)']]

# 直接复制到剪贴板
result.to_clipboard()

绘图代码

要绘制各月份平均涨跌幅可视化结果直接调用以下代码:

import matplotlib.pyplot as plt

# 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(10, 6))
# 上涨为绿色,下跌为红色
bar_colors = ['#2E8B57' if val > 0 else '#CD2626' for val in result['Adj Close (%)']]
plt.bar(result['Month (int)'], result['Adj Close (%)'], color=bar_colors)
plt.xlabel('月份')
plt.ylabel('平均涨跌幅(%)')
plt.title('21年各月份平均涨跌幅统计')
plt.xticks(range(1, 13))
plt.axhline(y=0, color='#333333', linestyle='-', linewidth=0.8)
plt.grid(axis='y', alpha=0.3)
plt.show()

样本数据验证结果

用你提供的样本片段计算,前4个月的平均结果如下:

  • 1月平均涨跌幅:-0.81%
  • 2月平均涨跌幅:-5.62%
  • 3月平均涨跌幅:1.63%
  • 4月平均涨跌幅:2.30%

内容的提问来源于stack exchange,提问作者jd_h2003

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 20:48:02