Skip to main content
 首页 » 编程设计

python Pandas : Stack and Enumerate Date to Create New Records

2024年09月07日8jirigala

我目前有一个具有以下通用格式的数据框:

id,transaction_dt,units,measure 
1,2014-01-06,30,30.5 
1,2014-02-04,5,22.6 

我希望完成的是:

根据将单位添加到 transaction_dt 作为天数来创建新记录,以创建如下所示的结果数据框:

id,enumerated_dt,measure 
1,2014-01-06,30.5 
1,2014-01-07,30.5 
1,2014-01-08,30.5 
... 
1,2014-02-05,30.5 
1,2014-02-04,22.6 
1,2014-02-05,22.6 
... 

我认为堆栈可能是解决方案的一部分,但我目前对如何以高效方式枚举/递增日期感到困惑。任何建议或解决方案将不胜感激!

请您参考如下方法:

编辑:乍一看,您似乎确实想要填补日期中的空白,然后前向填充您的数据,这可以很容易地完成,如下所示:

df.set_index('transaction_dt').resample('D').ffill() 

但是,如果您不想创建连续索引,而是想添加任意数量的行 N,您可以通过首先将“transaction_dt”移动到您的索引来实现:

df.set_index('transaction_dt', inplace=True) 

...然后使用此 lambda 函数(使用 numpy 方法):

add_n_dates = lambda n: df.index.repeat(n) + \ 
                        np.tile(np.arange(n)*pd.Timedelta('1 days'), df.index.size) 

... 将 n 日期添加到新索引的每个元素,最后重新索引 + 前向填充:

df.reindex(add_n_dates(5), method='ffill') 
 
#                  id  units  measure 
# transaction_dt                      
# 2014-01-06      1.0   30.0     30.5 
# 2014-01-07      1.0   30.0     30.5 
# 2014-01-08      1.0   30.0     30.5 
# 2014-01-09      1.0   30.0     30.5 
# 2014-01-10      1.0   30.0     30.5 
# 2014-02-04      1.0    5.0     22.6 
# 2014-02-05      1.0    5.0     22.6 
# 2014-02-06      1.0    5.0     22.6 
# 2014-02-07      1.0    5.0     22.6 
# 2014-02-08      1.0    5.0     22.6 

编辑#2:

再次假设您已经将索引设置为 transaction_dt,这可能是使用 units 中的值来确定要添加多少行的最简单方法。它使用 pd.date_range 通过传递 row.name(即它的索引值)作为起点和 row.units 创建必要的日期值> 作为要生成的周期数。

df.apply(lambda x: pd.Series(pd.date_range(x.name, periods=x.units)), axis=1). \ 
    stack(). \ 
    reset_index(level=1). \ 
    join(df['measure']). \ 
    drop('level_1', axis=1). \ 
    reset_index(). \ 
    rename(columns={0:'enumerated_dt'}) 
 
#    transaction_dt enumerated_dt  measure 
# 0      2014-01-06    2014-01-06     30.5 
# 1      2014-01-06    2014-01-07     30.5 
# 2      2014-01-06    2014-01-08     30.5 
# 3      2014-01-06    2014-01-09     30.5 
# 4      2014-01-06    2014-01-10     30.5 
# ... 
# 29     2014-01-06    2014-02-04     30.5 
# 30     2014-02-04    2014-02-04     22.6 
# 31     2014-02-04    2014-02-05     22.6 
# 32     2014-02-04    2014-02-06     22.6 
# 33     2014-02-04    2014-02-07     22.6 
# 34     2014-02-04    2014-02-08     22.6