我有一个每日数据框架(YYYY DD)的以下表格.每个日期在Type列中有两个类型,即"A“和"B”。
Date Type Value
2010-01-01 A 8
2010-01-01 B 5
2010-01-02 A 81
2010-01-02 B 7
......
2020-06-23 A 7
2020-06-23 B 7.1
2020-06-24 A 8
2020-06-24 B 11
...........
2021-10-09 A 5
2021-10-09 B 17
2021-10-10 A 1
2021-10-10 B 10我希望将未来日期添加到此数据框架中,直到当前月份的最后一个日期,以便未来日期的值等于该特定日期的过去10年的平均值,并键入。
例如:对于日期2021-10-11;类型A=2011年10月11日至2020年A类的平均值等等。我想把这些未来的值填到本月的最后一天。
Date Type Value
2021-10-11 A Avg for 11 Oct from 2011 to 2020
2021-10-11 B Avg for 11 Oct from 2011 to 2020
..........
2021-10-31 A Avg for 31 Oct from 2011 to 2020
2021-10-31 B Avg for 31 Oct from 2011 to 2020我怎样才能在熊猫身上做到这一点。
在对过去10年的数据进行过滤之后,我尝试了如下方法:
df = df.groupby([df.index.month, df.index.day, "Type"]).mean()但是,如何将值插入到dataframe?
谢谢
发布于 2021-10-11 10:31:54
我认为这个复杂的代码片段会有效的。我不知道有没有简单的方法。
df.index = df.Date
df["new"] = df.Date.astype(str).str[-5:]
df=df.groupby(["new","Type"],sort=False).expanding().mean().reset_index().sort_values(["Date","Type"]).reset_index(drop=True)
df["Value"] = df.groupby(["new","Type"]).shift().Value
df=df[["Date","Type","Value"]]https://stackoverflow.com/questions/69522604
复制相似问题