使用pandas数据框中的前向和后向填充填充缺失值(ffill和bfill)

时间:2017-01-11 11:11:15

标签: python pandas dataframe

初学者与熊猫数据帧。我有下面的数据集,列A和B(Test.csv)缺少值:

DateTime              A             B
01-01-2017 03:27        
01-01-2017 03:28        
01-01-2017 03:29    0.18127718  -0.178835737
01-01-2017 03:30    0.186923018 -0.183260853
01-01-2017 03:31        
01-01-2017 03:32        
01-01-2017 03:33    0.18127718  -0.178835737

我可以使用此代码使用向前传播填充值,但这仅适用于03:31和03:32,而不是03:27和03:28。

import pandas as pd
import numpy as np

df = pd.read_csv('test.csv', index_col = 0)
data = df.fillna(method='ffill')
ndata = data.to_csv('test1.csv')

结果:

   DateTime              A             B
    01-01-2017 03:27        
    01-01-2017 03:28        
    01-01-2017 03:29    0.18127718  -0.178835737
    01-01-2017 03:30    0.186923018 -0.183260853
    01-01-2017 03:31    0.186923018 -0.183260853
    01-01-2017 03:32    0.186923018 -0.183260853
    01-01-2017 03:33    0.18127718  -0.178835737

我怎么能包括' Bfill'使用backfil填写03:27和03:28的缺失值?

1 个答案:

答案 0 :(得分:18)

如果需要替换NaN值向前和向后填充,您可以使用ffillbfill

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

与带有参数的函数fillna相同:

data = df.fillna(method='ffill').fillna(method='bfill')