且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pandas :使用日期时间索引进行分组by向前填充

更新时间:2023-01-23 08:00:25

一种方法是使用transform函数在分组依据之后填充value列:

One way is to use the transform function to fill the value column after group by:

import pandas as pd
a['value'] = a.groupby('company')['value'].transform(lambda v: v.ffill())

a
#          company  value
#level_1        
#2010-01-01      a    1.0
#2010-01-01      b   12.0
#2011-01-01      a    2.0
#2011-01-01      b   12.0
#2012-01-01      a    2.0
#2012-01-01      b   14.0

为进行比较,原始数据框如下所示:

To compare, the original data frame looks like:

#            company    value
#level_1        
#2010-01-01        a      1.0
#2010-01-01        b     12.0
#2011-01-01        a      2.0
#2011-01-01        b      NaN
#2012-01-01        a      NaN
#2012-01-01        b     14.0