简体   繁体   English

用同一列中相邻行的平均值替换数据框中的零

[英]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.

相关问题 将 pandas 数据框列中的 null 值替换为 2D np.zeros() 数组 - Replace null values in pandas data frame column with 2D np.zeros() array 在 Pandas 的特定列上用值替换数据框的某些行 - Replace certain rows of data frame with values, on specific column, in Pandas Pandas 比较同一数据框中的列并根据比较替换值 - Pandas compare column in same data frame and replace values based on comparison Python pandas 如何用这些相同的值替换值之间的列中的零 - Python pandas how to replace zeros in a column between values with these same values 如果满足基于同一数据帧中其他2列的行值的条件,则在数据帧的列行中填充值 - Filling values in rows of column in a data frame, if condition based on 2 other columns row values in the same data frame is met 将一个数据帧中的零值列替换为另一个数据帧中的同名列的平均值 - Replace zero valued columns in one data frame with mean values of same name column in another data frame 如何将具有选定行平均值的行添加到数据框中 - How to add rows with the average values of selected rows into a data frame 如何有条件地根据同一数据帧另一列中的值对Pandas数据帧中的行进行计数? - How to count rows in a data frame in Pandas conditionally against values in another column of the same data frame? 如何根据特定列中的值对数据帧的行求平均? - How to average rows of a data frame based the value in a particular column? Pandas 根据同一数据框中另一列的条件替换列值 - Pandas Replace column values based on condition upon another column in the same data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM