gpt4 book ai didi

python - 如何将行添加到缺少日期(天)的表中,并使用从下面的行复制的值填充添加的行?

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

我有 table :

import pandas as pd
import numpy as np
df = pd.DataFrame([
("2019-01-22", np.nan, np.nan),
("2019-01-25", 10, 15),
("2019-01-28", 200, 260),
("2019-02-03", 3010, 3800),
("2019-02-05", 40109, 45009)],
columns=["date", "col1", "col2"])

Table_1

我需要在缺少日期(天)的表中添加新行。在添加的行中,在列 col1col2 中,必须有从表下方的行(从最近日期的行)复制的值。

我需要得到下表:

Table2

最佳答案

使用 pandas.to_datetimeasfreq:

df.set_index(pd.to_datetime(df['date'])).drop('date', 1).asfreq('1 d').bfill().reset_index()

输出:

         date     col1     col2
0 2019-01-22 10.0 15.0
1 2019-01-23 10.0 15.0
2 2019-01-24 10.0 15.0
3 2019-01-25 10.0 15.0
4 2019-01-26 200.0 260.0
5 2019-01-27 200.0 260.0
6 2019-01-28 200.0 260.0
7 2019-01-29 3010.0 3800.0
8 2019-01-30 3010.0 3800.0
9 2019-01-31 3010.0 3800.0
10 2019-02-01 3010.0 3800.0
11 2019-02-02 3010.0 3800.0
12 2019-02-03 3010.0 3800.0
13 2019-02-04 40109.0 45009.0
14 2019-02-05 40109.0 45009.0

关于python - 如何将行添加到缺少日期(天)的表中,并使用从下面的行复制的值填充添加的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56152562/

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