Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:如何用上一个非空值和下一个非空值的平均值填写n/a_Python_Pandas_Data Science - Fatal编程技术网

Python 熊猫:如何用上一个非空值和下一个非空值的平均值填写n/a

Python 熊猫:如何用上一个非空值和下一个非空值的平均值填写n/a,python,pandas,data-science,Python,Pandas,Data Science,我的数据框中有一些N/A值 df = pd.DataFrame({'A':[1,1,1,3], 'B':[1,1,1,3], 'C':[1,np.nan,3,5], 'D':[2,np.nan, np.nan, 6]}) print(df) A B C D 0 1 1 1.0 2.0 1 1 1 NaN NaN 2 1 1 3.0 NaN 3 3

我的数据框中有一些N/A值

df = pd.DataFrame({'A':[1,1,1,3],
              'B':[1,1,1,3],
              'C':[1,np.nan,3,5],
              'D':[2,np.nan, np.nan, 6]})
print(df)

    A   B   C   D
0   1   1   1.0 2.0
1   1   1   NaN NaN
2   1   1   3.0 NaN
3   3   3   5.0 6.0
如何在n/a值的列中填入其上一个非空值和下一个非空值的平均值? 例如,C列中的第二个值应填入(1+3)/2=2

期望输出:

    A   B   C   D
0   1   1   1.0 2.0
1   1   1   2.0 4.0
2   1   1   3.0 4.0
3   3   3   5.0 6.0

谢谢

使用
ffill
bfill
替换
NaN
s,然后使用聚合
平均值替换
groupby

df1 = pd.concat([df.ffill(), df.bfill()]).groupby(level=0).mean()
print (df1)
   A  B    C    D
0  1  1  1.0  2.0
1  1  1  2.0  4.0
2  1  1  3.0  4.0
3  3  3  5.0  6.0
详情:

print (df.ffill())
   A  B    C    D
0  1  1  1.0  2.0
1  1  1  1.0  2.0
2  1  1  3.0  2.0
3  3  3  5.0  6.0

print (df.bfill())
   A  B    C    D
0  1  1  1.0  2.0
1  1  1  3.0  6.0
2  1  1  3.0  6.0
3  3  3  5.0  6.0

这么好的逻辑+1.