gpt4 book ai didi

python - 使用 Python 用该列的平均值减去数据框中的每一列

转载 作者:太空狗 更新时间:2023-10-29 17:45:46 24 4
gpt4 key购买 nike

我正在寻找一种方法来查找 python 数据框中每一列的均值,并用该列的均值减去该列。

假设我有:

df = pd.DataFrame({'a': [1.5, 2.5], 'b': [0.25, 2.75], 'c': [1.25, 0.75]})

我想找到每一列的平均值,这将返回 (2,1.5,1) 并从 ab< 列中减去值c 分别。

这会给出,((-0.5,0.5),(-1.25, 1.5), (0.25,-0.25))

谁能帮我做这件事?

谢谢

最佳答案

您可以简单地使用 pandas 的 mean 函数

代码:

import pandas as pd
df = pd.DataFrame({'a': [1.5, 2.5], 'b': [0.25, 2.75], 'c': [1.25, 0.75]})

print "The data frame"
print df
print "The mean value"
print df.mean()
print "The value after subraction of mean"
print df -df.mean()

输出:

The data frame

a b c
0 1.5 0.25 1.25
1 2.5 2.75 0.75

The mean value

a 2.0
b 1.5
c 1.0
dtype: float64

The value after subraction of mean

a b c
0 -0.5 -1.25 0.25
1 0.5 1.25 -0.25

关于python - 使用 Python 用该列的平均值减去数据框中的每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com