How to replace NaNs by preceding values in pandas DataFrame?

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

    You can use fillna to remove or replace NaN values.

    NaN Remove

    import pandas as pd
    
    df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
    
    df.fillna(method='ffill')
         0    1    2
    0  1.0  2.0  3.0
    1  4.0  2.0  3.0
    2  4.0  2.0  9.0
    

    NaN Replace

    df.fillna(0) # 0 means What Value you want to replace 
         0    1    2
    0  1.0  2.0  3.0
    1  4.0  0.0  0.0
    2  0.0  0.0  9.0
    

    Reference pandas.DataFrame.fillna

提交回复
热议问题