【发布时间】:2021-07-30 14:20:18
【问题描述】:
我对 python 还很陌生,并试图将不同的函数应用于 pandas 中的不同组和多列。我一直在阅读,但似乎可以找到解决方案。
为了简单起见,下面是我想要做的。
import pandas as pd
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)
-
对于年龄列,我想使用以下代码
(df.groupby('group').transform('mean'))按组创建平均年龄 -
对于权重和分数列,我想使用以下代码
按组均值创建大均值中心数据(df.groupby('group').transform('mean').sub(df.mean()))
我在将这些放在一起运行在数据集上的函数中时遇到了一些问题。
@TYZ
我正在寻找的是如下函数:
def gmc(data):
d = []
# set the index of the dataframe to group
s = data.set_index('group')
# groupby and transform on level=0 to calculate the group mean
d.append(s.groupby(level=0).transform('mean').sub(s.mean(numeric_only=True)).reset_index())
# groupby and transform on level=0 to calculate the group mean and reset the index
d.append(data.groupby(data.iloc[:, 0]).age.transform('mean'))
return d
它为我提供了列年龄的分组平均值,以及权重和分数的组平均中心值,如下所示:
group age weight score
0 1 33.75 3.928571 3.0
1 1 33.75 3.928571 3.0
2 1 33.75 3.928571 3.0
3 2 36.00 -5.238095 -4.0
4 2 36.00 -5.238095 -4.0
5 1 33.75 3.928571 3.0
6 2 36.00 -5.238095 -4.0
【问题讨论】:
标签: python-3.x pandas dataframe