从每月重新采样到每周是否从周一开始?

2024-04-25 22:34:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df:

year | month | A
2020 | 1     | 4
2020 | 2     | 4
2020 | 3     | 6
2020 | 4     | 5
2020 | 5     | 5

我想将其重新采样到weekly,并将一年中的一周作为一个新列。 每个月的每个星期都应该从a列中获得相等的月值

df["day"] = 1
df["date"] = df[["year", "month", "day"]].astype(str).apply(lambda x: pd.to_datetime('-'.join(x)), 1)
df = df.set_index("date")
df = df.drop(["year", "month", "day"], axis=1)

结果:

date       | A
2020-01-01 | 4
2020-02-01 | 4
2020-03-01 | 6
2020-04-01 | 5
2020-05-01 | 5

现在我重新采样:

s = df.resample(rule="W").mean()
s = s.groupby(s["A"].notnull().cumsum()).["A"].transform(lambda x : x.sum()/len(x)).to_frame()
s = s.reset_index()

s["week_of_year"] = s["date"].dt.isocalendar().week
s = s.set_index("date")

结果:

date       | A   | week_of_year
2020-01-03 | 0.8 | 53
2020-01-10 | 0.8 | 1
2020-01-17 | 0.8 | 2
2020-01-24 | 0.8 | 3 
2020-01-31 | 0.8 | 4
2020-02-07 | 1   | 5

问题:为什么第一周从2020-01-03开始?那是星期五,不是星期一。我理解年份的周=53,因为2019年12月底是星期一,这是ISO标准

但是我的下一周不是应该在2020-01-06==星期一开始吗


Tags: ofto数据lambdadfdateindexyear