How to replace NaNs by preceding values in pandas DataFrame?

前端 未结 9 2082
無奈伤痛
無奈伤痛 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:41

    One thing that I noticed when trying this solution is that if you have N/A at the start or the end of the array, ffill and bfill don't quite work. You need both.

    In [224]: df = pd.DataFrame([None, 1, 2, 3, None, 4, 5, 6, None])
    
    In [225]: df.ffill()
    Out[225]:
         0
    0  NaN
    1  1.0
    ...
    7  6.0
    8  6.0
    
    In [226]: df.bfill()
    Out[226]:
         0
    0  1.0
    1  1.0
    ...
    7  6.0
    8  NaN
    
    In [227]: df.bfill().ffill()
    Out[227]:
         0
    0  1.0
    1  1.0
    ...
    7  6.0
    8  6.0
    

提交回复
热议问题