How to replace NaNs by preceding values in pandas DataFrame?

前端 未结 9 2076
無奈伤痛
無奈伤痛 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 07:00

    You can use pandas.DataFrame.fillna with the method='ffill' option. 'ffill' stands for 'forward fill' and will propagate last valid observation forward. The alternative is 'bfill' which works the same way, but backwards.

    import pandas as pd
    
    df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
    df = df.fillna(method='ffill')
    
    print(df)
    #   0  1  2
    #0  1  2  3
    #1  4  2  3
    #2  4  2  9
    

    There is also a direct synonym function for this, pandas.DataFrame.ffill, to make things simpler.

提交回复
热议问题