[英]Replace zeros in the data frame with average values of adjacent rows in the same column
I have imported data from excel file into a variable df using pandas.我已经使用 Pandas 将数据从 excel 文件导入到变量 df 中。 Some of the values are zeros.
一些值为零。 I need to replace this values with the average of the values in the upper row and lower row of the same column.
我需要用同一列的上一行和下一行中的值的平均值替换这些值。 Please suggest how I can iterate and calculate the average values.
请建议我如何迭代和计算平均值。
use intrpolate
after replacing 0s with NaNs用 NaN 替换 0 后使用内
intrpolate
import numpy as np
df = pd.DataFrame({ 'A' : [2,3,0,1]})
df.replace(0,np.nan, inplace = True)
df.interpolate(inplace=True)
df
this returns这返回
A
0 2.0
1 3.0
2 2.0
3 1.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.