如何用 pandas 数据框中的第一行和相应行之间的列平均值填充特定值 [英] How to fill a particular value with mean value of the column between first row and the corresponding row in pandas dataframe

查看:80
本文介绍了如何用 pandas 数据框中的第一行和相应行之间的列平均值填充特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的df,

A   B   C   D   E
1   2   3   0   2
2   0   7   1   1
3   4   0   3   0
0   0   3   4   3

我正在尝试用第一行和对应列的0值行之间的mean()值替换所有0,

I am trying to replace all the 0 with mean() value between the first row and the 0 value row for the corresponding column,

我的预期输出是

A       B       C           D       E
1.0     2.00    3.000000    0.0     2.0
2.0     1.00    7.000000    1.0     1.0
3.0     4.00    3.333333    3.0     1.0
1.5     1.75    3.000000    4.0     3.0


推荐答案

问题需要先前的平均值值,如果每列有多个 0 的话,那么创建向量化解决方案就真的很成问题:

Here is main problem need previous mean value if multiple 0 per column, so realy problematic create vectorized solution:

def f(x):
    for i, v in enumerate(x):
        if v == 0: 
            x.iloc[i] = x.iloc[:i+1].mean()
    return x

df1 = df.astype(float).apply(f)
print (df1)

     A     B         C    D    E
0  1.0  2.00  3.000000  0.0  2.0
1  2.0  1.00  7.000000  1.0  1.0
2  3.0  4.00  3.333333  3.0  1.0
3  1.5  1.75  3.000000  4.0  3.0

更好的解决方案:

#create indices of zero values to helper DataFrame
a, b = np.where(df.values == 0)
df1 = pd.DataFrame({'rows':a, 'cols':b})
#for first row is not necessary count means
df1 = df1[df1['rows'] != 0]
print (df1)
   rows  cols
1     1     1
2     2     2
3     2     4
4     3     0
5     3     1

#loop by each row of helper df and assign means
for i in df1.itertuples():
    df.iloc[i.rows, i.cols] = df.iloc[:i.rows+1, i.cols].mean()

print (df)
     A     B         C  D    E
0  1.0  2.00  3.000000  0  2.0
1  2.0  1.00  7.000000  1  1.0
2  3.0  4.00  3.333333  3  1.0
3  1.5  1.75  3.000000  4  3.0

另一个类似的解决方案(平均值为):

Another similar solution (with mean of all pairs):

for i, j in zip(*np.where(df.values == 0)):
    df.iloc[i, j] = df.iloc[:i+1, j].mean()
print (df)

     A     B         C    D    E
0  1.0  2.00  3.000000  0.0  2.0
1  2.0  1.00  7.000000  1.0  1.0
2  3.0  4.00  3.333333  3.0  1.0
3  1.5  1.75  3.000000  4.0  3.0

这篇关于如何用 pandas 数据框中的第一行和相应行之间的列平均值填充特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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