【问题标题】:Aggregating Fiscal Week data into monthly sum in pandas将财政周数据汇总为 pandas 中的每月总和
【发布时间】:2016-07-08 02:10:37
【问题描述】:

我有一个如下所示的数据集:

      YR_FW    YIELD
0    201401     12.3
1    201402     10.2
2    201403     7.2
3    201404     8.0
4    201405     1.2
...  ....     ....
96   201446     102.3
97   201447     101.7
98   201448     89.5
99   201449     72.2
100  201450     88.0
101  201451     98.89

我想汇总(总和)这样我有 12 个月。它可能看起来像这样:

Months    Summed_YLD
1            value
2            value
...         ...
11           value
12           value

注意:YR_FW 有时会有缺失值。例如201427 不在数据框中。

注意2:如果案例重叠,则应汇总到结束月份。一周从星期一开始,到星期日结束(这不是 5 天的一周)。

【问题讨论】:

  • 一周重叠两个月应该怎么办?是否应该将这些值汇总到起始月份?月底?两者分不开?
  • 另一个澄清:你的星期是从一周中的哪一天开始的?
  • @root:这些都是非常好的问题。如果案例重叠两周,您将汇总到结束月份。一周以周日结束,因此从周一开始。我会将这个添加到我的问题中。

标签: python pandas


【解决方案1】:

我会先将这些转换为日期时间:

In [11]: df["YR_FW"] = pd.to_datetime(df["YR_FW"].astype("str") + "-0", format="%Y%W-%w")

In [12]: df
Out[12]:
       YR_FW  YIELD
0 2014-01-12   12.3
1 2014-01-19   10.2
2 2014-01-26    7.2
3 2014-02-02    8.0
4 2014-02-09    1.2

请注意,%W 指定一周从星期一开始,'-0' 指定一周内的星期日。因此,结果日期将是指定的一周的最后一天。

现在您可以使用 dt 访问器来提取一周中月份的最后一天:

In [13]: df.groupby(df["YR_FW"].dt.month).sum()
Out[13]:
       YIELD
YR_FW       
1       29.7
2        9.2

【讨论】:

  • 感谢您的回复。请注意,“YR_FW”是每周值。因此,201402 是 1 月的第二周,而不是 2 月。我想将 52 周合并为 12 个月。
  • @Rohit 嗯,似乎 %W 或 %U 应该这样做,但它似乎对我不起作用:/ docs.python.org/2/library/…
  • @Rohit 啊哈,你需要这样做:pd.to_datetime(df["YR_FW"].astype("str") + "-0", format="%Y%W-%w") 注意:astype 可能不是必需的。
  • 是的,我必须将类型更改为 str 才能正常工作。然而,这如何解决以下问题:(1)当一周重叠两个月时会发生什么。它是如何聚合的? (2) 什么时候缺周?这些问题由上面的root提出并且非常中肯,以便得到正确的答案。谢谢!
  • @AndyHayden 评论中的to_datetime 转换是正确的。 %W 指定一周从星期一开始,'-0' 指定一周内的星期日。因此,结果日期将是指定的一周的最后一天。然后,当按照他的回答执行groupby 时,它将汇总到结束月份。
【解决方案2】:

很遗憾,我没有足够的数据来全面检查代码,但这就是我现在所做的。如果我们假设我们有:

import pandas as pd
import numpy as np

df = pd.DataFrame({"YR_FW":[201401,201402,201403,201405,201506],"YIELD":[12.3,10.2,7.2,1.2,3.8]})

     YR_FW    YIELD
0    201401     12.3
1    201402     10.2
2    201403     7.2
3    201405     1.2
4    201506     3.8

缺少第 3 行以符合您的实际数据,并添加了不同的年份。我们可以如下进行:

df_pd_range = pd.period_range("01/01/2014","02/07/2016", freq="W") #Here you place the period of your data, I elongated till 2016 to test code
df.YR_FW = df.YR_FW.astype(str).map(lambda a_: a_[:4] + "-" + a_[4:])
a_ = [np.logical_and(df_pd_range.year == int(df.YR_FW.iloc[i][:4]),df_pd_range.week==int(df.YR_FW.iloc[i][5:])) for i in range(len(df))] #choose only the period that is present in the data
b_ = [df_pd_range[i][0] for i in a_]
arrays = [[i.year for i in b_],[i.month for i in b_] ]
index = pd.MultiIndex.from_arrays(arrays, names=["year", "month"])
df.set_index(index, inplace=True)
df.groupby(level=[0,1]).mean() #Here you obtain mean data grouped by week and year

告诉我进展如何

【讨论】:

  • 感谢您解决此问题。我想要安迪的回答所做的一切都在熊猫中。它也非常优雅。尽管如此,还是感谢您的努力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多