gpt4 book ai didi

python - Pandas :从每周到每天重新采样,并带有偏移量

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:03 24 4
gpt4 key购买 nike

我想从每周到每天对以下数据帧重新采样,然后填充缺失值。

注意:2018-01-07 和 2018-01-14 是星期日。

         Date  Val
0 2018-01-07 1
1 2018-01-14 2

我试过了。

df.Date = pd.to_datetime(df.Date)
df.set_index('Date', inplace=True)
offset = pd.offsets.DateOffset(-6)

df.resample('D', loffset=offset).ffill()

Val
Date
2018-01-01 1
2018-01-02 1
2018-01-03 1
2018-01-04 1
2018-01-05 1
2018-01-06 1
2018-01-07 1
2018-01-08 2

但是我想要

         Date  Val
0 2018-01-01 1
1 2018-01-02 1
2 2018-01-03 1
3 2018-01-04 1
4 2018-01-05 1
5 2018-01-06 1
6 2018-01-07 1
7 2018-01-08 2
8 2018-01-09 2
9 2018-01-10 2
10 2018-01-11 2
11 2018-01-12 2
12 2018-01-13 2
13 2018-01-14 2

我做错了什么?

最佳答案

您可以通过为 datetime 减去 offset 手动添加新的最后一行:

df.loc[df.index[-1] - offset] = df.iloc[-1]
df = df.resample('D', loffset=offset).ffill()
print (df)
Val
Date
2018-01-01 1
2018-01-02 1
2018-01-03 1
2018-01-04 1
2018-01-05 1
2018-01-06 1
2018-01-07 1
2018-01-08 2
2018-01-09 2
2018-01-10 2
2018-01-11 2
2018-01-12 2
2018-01-13 2
2018-01-14 2

关于python - Pandas :从每周到每天重新采样,并带有偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55901304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com