python-3.x - 在 Pandas 中按组均值创建以总均值为中心的变量

标签 python-3.x pandas dataframe pandas-groupby aggregate

我正在尝试按组创建均值中心变量。

样本数据为:

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/

相关文章:

python - Pandas int 或 float 列到百分比分布

python - 拆分 pandas 数据帧索引中的值

python - 在Python中合并两个数据框

python - 如何打印 python 数组中的列?

python-3.x - 将用 Canvas 绘制的矩形的填充设置为 RGB 值

python-3.x - Python 项目的预提交 Hook 失败

python - Pandas 将多行作为一行,添加特定列

python-2.7 - python Pandas : set a value of column based on another value of a column in a list

python - 如何提取pandas DataFrame中的属性名称和最大共现计数?

python - 根据列值将数据从一个 pandas 数据框复制到另一个,并用逗号分隔