Subtract every column in dataframe with the mean of that column with Python
You could simply use the mean function of pandas
Code:
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()
Output:
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
try this:
>>> 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
Pythonic way:
>>> df - df.mean()
a b c
0 -0.5 -1.25 0.25
1 0.5 1.25 -0.25