gpt4 book ai didi

python - Pandas 创建新的日期行和正向填充列值

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

我有一个这样的数据框:

id     date       value
1 12/01/2016 5
1 25/02/2016 7
1 10/03/2017 13
2 02/04/2016 0
2 06/07/2016 1
2 18/04/2017 6

对于每个 id,都有一个带有值的开始日期,每隔几个月就会有另一行带有一个日期和一个值。我想为每个 id 创建一个时间序列。所以我想在第二天(直到今天)插入新行,其中的值将从前一行向前填充。

所以数据框变成了:

id     date       value
1 12/01/2016 5
1 13/01/2016 5
1 14/01/2016 5
1 15/01/2016 5
...
1 20/04/2017 13
...
2 18/04/2017 6
2 19/04/2017 6
2 20/04/2017 6

例如对类似问题的回答:Appending datetime rows and forward filling data in pandas dataframe

但我的数据框没有日期时间索引。

感谢任何帮助!

最佳答案

考虑groupbymerge 方法:

import pandas as pd
from io import StringIO
from datetime import date

txt= """
id date value
1 12/01/2016 5
1 25/02/2016 7
1 10/03/2017 13
2 02/04/2016 0
2 06/07/2016 1
2 18/04/2017 6
"""

df = pd.read_table(StringIO(txt), sep="\s+", parse_dates=[1], dayfirst=True)

def expand_dates(ser):
return pd.DataFrame({'date': pd.date_range(ser['date'].min(), date.today(), freq='D')})

newdf = df.groupby(['id']).apply(expand_dates).reset_index()\
.merge(df, how='left')[['id', 'date', 'value']].ffill()

关于python - Pandas 创建新的日期行和正向填充列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43526973/

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