Efficient solution for forward filling missing values in a pandas dataframe column?

前端 未结 3 1903
盖世英雄少女心
盖世英雄少女心 2020-12-18 13:00

I need to forward fill values in a column of a dataframe within groups. I should note that the first value in a group is never missing by construction. I have the following

3条回答
  •  忘掉有多难
    2020-12-18 13:07

    Using ffill() directly will give the best results. Here is the comparison

    %timeit df.b.ffill(inplace = True)
    best of 3: 311 µs per loop
    
    %timeit df['b'] = df.groupby('a')['b'].transform(lambda x: x.fillna(method='ffill'))
    best of 3: 2.34 ms per loop
    
    %timeit df['b'] = df.groupby('a')['b'].fillna(method='ffill')
    best of 3: 4.41 ms per loop
    

提交回复
热议问题