[英]In python, how can I replace a specific value in a data frame with its column mean?
I have found questions about replacing values in a column, but I don't know how to specifically replace each value with its column mean.我发现了有关替换列中的值的问题,但我不知道如何专门用列均值替换每个值。 For example, in the code provided, how would I replace each -1 with the mean of the column the -1 was found in?
例如,在提供的代码中,如何将每个 -1 替换为 -1 所在列的平均值? I'm pretty new to python and don't know where to go
我对 python 很陌生,不知道 go 在哪里
df = pd.DataFrame({"A" : [1, 2, 4, -1, 6, 7, 8],
"B" : [2, 4, -1, 8, 10, 6, 7],
"C" : [20, -1, 4, 8, 19, 1, 7] })
Use DataFrame.mask
with compare by DataFrame.eq
for ==
for set mean
:使用
DataFrame.mask
与DataFrame.eq
比较==
设置mean
:
df = df.mask(df.eq(-1), df.mean(), axis=1)
print (df)
A B C
0 1.000000 2.000000 20.000000
1 2.000000 4.000000 8.285714
2 4.000000 5.142857 4.000000
3 3.857143 8.000000 8.000000
4 6.000000 10.000000 19.000000
5 7.000000 6.000000 1.000000
6 8.000000 7.000000 7.000000
Detail :详情:
print (df.mean())
A 3.857143
B 5.142857
C 8.285714
dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.