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

Subtract every column in dataframe with the mean of that column with Python

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

假设我有:

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

我想求出每列的平均值,即 return (2,1.5,1) 并减去 abc 列的值分别。

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

有人可以帮我做这件事吗?

谢谢

试试这个:

>>> df
     a     b     c
0  1.5  0.25  1.25
1  2.5  2.75  0.75
>>> df.columns
Index([u'a', u'b', u'c'], dtype='object')
>>> for x in df.columns:
...     df[x] = df[x] - df[x].mean()
... 
>>> df
     a     b     c
0 -0.5 -1.25  0.25
1  0.5  1.25 -0.25

Python 方式:

>>> df - df.mean()
     a     b     c
0 -0.5 -1.25  0.25
1  0.5  1.25 -0.25

您可以简单地使用 mean function of pandas

代码:

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