Filling missing values using forward and backward fill in pandas dataframe (ffill and bfill)

后端 未结 1 1727
梦如初夏
梦如初夏 2020-12-08 03:15

Beginner with panda dataframes. I have this data set below with missing values for column A and B (Test.csv):

DateTime              A             B
01-01-201         


        
相关标签:
1条回答
  • 2020-12-08 03:35

    You can use ffill and bfill if need replace NaN values forward and backward filling:

    print (df)
                             A         B
    DateTime                            
    01-01-2017 03:27       NaN       NaN
    01-01-2017 03:28       NaN       NaN
    01-01-2017 03:29  0.181277 -0.178836
    01-01-2017 03:30  0.186923 -0.183261
    01-01-2017 03:31       NaN       NaN
    01-01-2017 03:32       NaN       NaN
    01-01-2017 03:33  0.181277 -0.178836
    
    data = df.ffill().bfill()
    print (data)
                             A         B
    DateTime                            
    01-01-2017 03:27  0.181277 -0.178836
    01-01-2017 03:28  0.181277 -0.178836
    01-01-2017 03:29  0.181277 -0.178836
    01-01-2017 03:30  0.186923 -0.183261
    01-01-2017 03:31  0.186923 -0.183261
    01-01-2017 03:32  0.186923 -0.183261
    01-01-2017 03:33  0.181277 -0.178836
    

    Which is same as the function fillna with parameters:

    data = df.fillna(method='ffill').fillna(method='bfill')
    
    0 讨论(0)
提交回复
热议问题