简体   繁体   English

在 python 中,如何将数据框中的特定值替换为其列均值?

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

相关问题 如何将数据框列中的每个值移到其自己的列中? - How can I move each value in a data frame column into its own column? 如何通过在python中指定列索引将列表插入数据帧中的特定列? - How Can I insert a list into a specific column in a data frame by specifying the column index in python? 如何从 python 中的 Spark 数据框中访问特定列? - How can I access a specific column from Spark Data frame in python? 如何在python中给定特定条件的情况下替换列? - How can I replace a column given a specific condition in python? 如何用 python 中的特定值替换列的值? - How replace values of column with specific value in python? 仅在“.”时替换是python中数据框列中的唯一值 - Replace only if "." is the only value in a data frame column in python 如何在此数据框中重复地将平均值链接到另一列的中间值? - How can I link the mean values to the middle values of the other column repetitively in this data frame? 如何用列值替换pandas数据框中的每个值? - How to replace each value in pandas data frame with column value? 如何在Python的数据框中使用浮点数据替换列中的Nan - How to replace Nan from column with float data in a data frame in python 如何更改数据框 python 中的值? - how can i change value in a data frame python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM