熊猫数据帧的初学者。我在下面有这个数据集,其中包含 A 列和 B 列(测试.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"以填充 03:27 和 03:28 的缺失值?
如果需要
,您可以使用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
这与带有参数的函数fillna
相同:
data = df.fillna(method='ffill').fillna(method='bfill')