使用向前和向后填充 pandas 数据框(填充和填充)来填充缺失值 [英] Filling missing values using forward and backward fill in pandas dataframe (ffill and bfill)

查看:1002
本文介绍了使用向前和向后填充 pandas 数据框(填充和填充)来填充缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有熊猫数据框的初学者.我在下面设置了此数据集,但缺少A和B列(Test.csv)的值:

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-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.

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.

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

如何使用backfil包含填充"来填充03:27和03:28的缺失值?

How could I include the 'Bfill' to fill in the missing values for 03:27 and 03:28 using the backfil?

推荐答案

您可以使用

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

与函数 fillna ,参数:

Which is same as the function fillna with parameters:

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

这篇关于使用向前和向后填充 pandas 数据框(填充和填充)来填充缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆