我正在尝试按组创建均值中心变量。
样本数据为:
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)
我正在尝试编写一个函数,该函数将按组估计数据集中所有变量的总均值居中变量。我尝试的代码如下:
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
但是,当我这样做时,它返回一个数据框,其中分组变量组也被转换,而不是像括号 [] 中那样获取组
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
只是寻找一些关于如何修复代码以保持分组变量 group 原样而不是对其进行转换的想法。
最佳答案
如果您可以接受其他解决方案,您所做的也可以直接通过 groupby.transform
完成。
out = ((df.groupby("group").transform("mean")-df.mean())
.fillna({"group":df['group']}).reindex(columns=df.columns))
print(out)
group age weight score
0 1 -0.964286 3.928571 3.0
1 1 -0.964286 3.928571 3.0
2 1 -0.964286 3.928571 3.0
3 2 1.285714 -5.238095 -4.0
4 2 1.285714 -5.238095 -4.0
5 1 -0.964286 3.928571 3.0
6 2 1.285714 -5.238095 -4.0
关于python-3.x - 在 Pandas 中按组均值创建以总均值为中心的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67078073/