使用向前和向后填充 Pandas 数据帧(填充和填充)填充缺失值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41589365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filling missing values using forward and backward fill in pandas dataframe (ffill and bfill)
提问by warrenfitzhenry
Beginner with panda dataframes. I have this data set below with missing values for column A and B (Test.csv):
Pandas数据帧初学者。我有以下数据集,其中 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
I can use this code to fill in values using forward propagation, but this only fills in for 03:31 and 03:32, and not 03:27 and 03:28.
我可以使用此代码使用前向传播填充值,但这仅填充 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')
results in:
结果是:
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
How could I include the 'Bfill' to fill in the missing values for 03:27 and 03:28 using the backfil?
我如何包含“Bfill”以使用 backfil 填充 03:27 和 03:28 的缺失值?
回答by jezrael
You can use ffill
and bfill
if need replace NaN
values forward and backward filling:
您可以使用ffill
并且bfill
如果需要替换NaN
向前和向后填充的值:
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:
fillna
与带参数的函数相同:
data = df.fillna(method='ffill').fillna(method='bfill')