Forward fill all except last value in python pandas dataframe

前端 未结 2 1678
离开以前
离开以前 2021-02-06 10:28

I have a dataframe in pandas with several columns I want to forward fill the values for. At the moment I\'m doing:

columns = [\'a\', \'b\', \'c\']
for column in          


        
2条回答
  •  生来不讨喜
    2021-02-06 11:30

    You can use last_valid_index in a lambda function to just ffill up to that point.

    df = pd.DataFrame({
        'A': [1, None, None, None], 
        'B': [1, 2, None, None], 
        'C': [1, None, 3, None], 
        'D': [1, None, None, 4]})
    
    >>> df
        A   B   C   D
    0   1   1   1   1
    1 NaN   2 NaN NaN
    2 NaN NaN   3 NaN
    3 NaN NaN NaN   4
    
    >>> df.apply(lambda series: series.loc[:series.last_valid_index()].ffill())
        A   B   C  D
    0   1   1   1  1
    1 NaN   2   1  1
    2 NaN NaN   3  1
    3 NaN NaN NaN  4
    

提交回复
热议问题