How to replace NaNs by preceding values in pandas DataFrame?

前端 未结 9 2080
無奈伤痛
無奈伤痛 2020-11-22 06:04

Suppose I have a DataFrame with some NaNs:

>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, N         


        
9条回答
  •  长情又很酷
    2020-11-22 06:49

    You could use the fillna method on the DataFrame and specify the method as ffill (forward fill):

    >>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
    >>> df.fillna(method='ffill')
       0  1  2
    0  1  2  3
    1  4  2  3
    2  4  2  9
    

    This method...

    propagate[s] last valid observation forward to next valid

    To go the opposite way, there's also a bfill method.

    This method doesn't modify the DataFrame inplace - you'll need to rebind the returned DataFrame to a variable or else specify inplace=True:

    df.fillna(method='ffill', inplace=True)
    

提交回复
热议问题