I am trying to create grand mean centered variables by groups.
The sample data is:
import pandas as pd
import numpy as np
dat = {
'group': ['1', '1', '1', '2', '2', '1', '2'],
'age': [40, 29, 34, 35, 37, 32, 36],
'weight': [150, 175, 135, 125, 189, 178, 137],
'score': [98.0, 77.0, 88.0, 78.0, 78.0, 85.0, 84.0]
}
df = pd.DataFrame(data=dat)
I am trying to write a function that will estimate the grand mean centered variables by groups for all the variables in the dataset. My code to attempt that is below:
def group_mean_centered(x):
d = []
d.append(x.groupby(x.iloc[:, 0]).transform('mean') - x.iloc[:,0:].mean())
d = np.asarray(d)
d_ = d.reshape(-1,len(x.columns))
dd = pd.DataFrame(d_, columns=[list(x.columns.values)])
return dd
However, when I do that, it returns a dataframe where the grouping variable, group, is also transformed, instead of getting the groups as in the brackets []
group age weight score
0 -0.428571 [1] -0.964286 3.928571 3.0
1 -0.428571 [1] -0.964286 3.928571 3.0
2 -0.428571 [1] -0.964286 3.928571 3.0
3 0.571429 [2] 1.285714 -5.238095 -4.0
4 0.571429 [2] 1.285714 -5.238095 -4.0
5 -0.428571 [1] -0.964286 3.928571 3.0
6 0.571429 [2] 1.285714 -5.238095 -4.0
Just looking for some ideas on how to fix the code to keep the grouping variable, group, as is instead of transforming it.