用之前和之后的平均值填充包含NaN的单元格 [英] Fill cell containing NaN with average of value before and after

查看:82
本文介绍了用之前和之后的平均值填充包含NaN的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用缺失值之前和之后的单元格平均值填充熊猫数据框中的缺失值.因此,如果为[1,NaN,3],则NaN值为2,因为(1 + 3)/2.我找不到任何方法可以通过Pandas或Scikit-learn做到这一点.有什么办法吗?

I would like to fill missing values in a pandas dataframe with the average of the cells directly before and after the missing value. So if it was [1, NaN, 3], the NaN value would be 2 because (1 + 3)/2. I could not find any way to do this with Pandas or Scikit-learn. Is there any way to do this?

推荐答案

考虑此数据框

df = pd.DataFrame({'val': [1,np.nan, 4, 5, np.nan, 10]})

    val
0   1.0
1   NaN
2   4.0
3   5.0
4   NaN
5   10.0

您可以将fillna与shift()一起使用以获取所需的输出

You can use fillna along with shift() to get the desired output

df.val = df.val.fillna((df.val.shift() + df.val.shift(-1))/2)

你得到

    val
0   1.0
1   2.5
2   4.0
3   5.0
4   7.5
5   10.0

这篇关于用之前和之后的平均值填充包含NaN的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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