【问题标题】:Finding % increase for each month on average in a multiple year dataset在多年数据集中找到平均每个月的百分比增长
【发布时间】:2023-03-09 16:59:01
【问题描述】:

我有一个来自 yahoo Finance 的数据集,我正在尝试按月分组(我已经这样做了),然后绘制该月在年度周期中的平均百分比变化(数据可以追溯到 21 年)。例如,我有 21 个 1 月,平均 % 增加/减少 1 月的总和,21 月 21 日,平均 % 增加/减少,2 月的总和,等等。

在玩了大约 2 个小时之后,我无法将它正确地聚集在一起,这让我发疯了。我尝试过使用pd.Grouperpd.groupby 以及使用日期时间的变体来隔离月份,或者给月份分配一个指定的数字来分组,但我没有运气。

我正在寻找的预期结果应该是这样的(~ 是日期时间 YYYYMMDD 格式的占位符)

     Adj Close (%)  Month (int)
Date          8.5            1
~            -3.2            2
~            7.18            3
~           -1.8%            4
~            ...            ...

使用pd.to_clipboard创建这个数据(应该可以使用pd.read_clipboard读取)

每月数据示例:(日期是索引列,因此这是功能上的时间序列数据)

           Adj Close
Date    
1999-09-30  NaN
1999-10-31  6.253954
1999-11-30  1.906186
1999-12-31  5.784389
2000-01-31  -5.090355
2000-02-29  -2.010808
2000-03-31  9.671983
2000-04-30  -3.079576
2000-05-31  -2.191505
2000-06-30  2.393355
2000-07-31  -1.634128
2000-08-31  6.069910
2000-09-30  -5.348297
2000-10-31  -0.494949
2000-11-30  -8.006861
2000-12-31  0.405345
2001-01-31  3.463658
2001-02-28  -9.229074
2001-03-31  -6.420471
2001-04-30  7.681436

【问题讨论】:

  • @Corralien 道歉,格式错误。编辑OP

标签: python-3.x pandas matplotlib


【解决方案1】:

你在找那个吗:

dti = pd.date_range('1999', '2020', freq='M', name='Date')
df1 = pd.DataFrame({'Adj Close': np.random.randint(1, 30, len(dti))}, index=dti)

out = df1.groupby(df1.index.month)['Adj Close'] \
         .apply(lambda x: x.pct_change().mean()) \
         .rename_axis('Month').reset_index()

输出:

>>> out
    Month  Adj Close
0       1   1.185047
1       2   2.057344
2       3   1.116738
3       4   1.531147
4       5   0.981474
5       6   2.025258
6       7   0.914078
7       8   0.301812
8       9   0.710584
9      10   1.498942
10     11   1.910080
11     12   1.643428

【讨论】:

  • 我相信这是正确的,我得到了 9 月的 -inf 值和 6 月的 -22% 值,这很奇怪,因为我已经清理了数据并且没有任何问题。澄清一下,df1 将是我发布的数据集,对吗?
  • 我随机生成了 df1 的值。尝试您发布的数据集。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2021-04-30
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多