Pandas的缺失值填充

在写例子的时候用到了缺失值的填充,于是想用一下method这个参数传入’ffill’来实现.
但是发现,这个填充方法并不全如我意.
仔细实验后发现,这其中有些需要注意的点.

fill_test = Series([111, 222, 533, 644, 299], index=[1, 2, 3, 7, 11])
print(fill_test)

fill_test_1 = fill_test.reindex(index=[1, 2, 3, 7, 11, 4], method='ffill')
print(fill_test_1)

fill_test_1[4] = 555
print(fill_test_1)

fill_test_2 = fill_test_1.sort_index().reindex(index=[1, 2, 3, 8], method='ffill')
print(fill_test_2)

fill_test_3 = fill_test_1.sort_index().reindex(index=[1, 2, 3, 8], method='nearest')
print(fill_test_3)    
fill_test_4 = fill_test_1.sort_index().reindex(index=[1, 2, 3, 9], method='nearest')
print(fill_test_4)

如上,你需要保证你的原始数据的index 是单调递增的.(值不影响)
当你在第二步添加了一个4以后,就改变了这一属性.
所以想要修改index,需要一个sort_index().
如果你reindex 的时候,填入的index也非单调递增的,则也需要使用sort_index()来排序保障.
另外补充的值是根据你原始数据集中的前向填充,即第四步中的8对应的值,是原数据中7对应的填充,而非对3对应数据的复制.
而第五步中,nearest方法则实现了最靠近的填充.原始数据中,有索引为7和索引为11的数据了.这时对索引为8和9的值进行填充,可以看到前一个显而易见,后一个则使用了索引为11的数据.
以上.

refer:
https://stackoverflow.com/questions/37982170/pandas-reindex-and-fill-missing-values-index-must-be-monotonic
https://stackoverflow.com/questions/31285508/valueerror-index-must-be-monotonic-increasing-or-decreasing
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值