【问题标题】:Apply Different Functions to Different Groups and Multiple Columns in Pandas在 Pandas 中对不同的组和多列应用不同的功能
【发布时间】: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)
  1. 对于年龄列,我想使用以下代码(df.groupby('group').transform('mean'))按组创建平均年龄

  2. 对于权重和分数列,我想使用以下代码 (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


    【解决方案1】:

    这应该可行:

    df.groupby("group").agg({
        "age": np.mean,
        "weight": lambda x: np.mean(x) - df["weight"].mean(),
        "score": lambda x: np.mean(x) - df["score"].mean()})
    
    # output
             age    weight  score
    group                        
    1      33.75  3.928571    3.0
    2      36.00 -5.238095   -4.0
    

    更新

    我不确定您还有哪些其他列以及您正在应用哪些其他功能。我注意到的是,您的所有 3 列都应用了均值函数,然后对于 weightscore,您还有一个额外的步骤来减去总体平均值。所以我会这样做:

    res = df.groupby("group").agg(np.mean)
    for c in ["weight", "score"]:
        res[c] = res[c] - df[c].mean()
    

    【讨论】:

    • 我的数据中有超过三列,所以我一直在寻找一种不单独处理每一列的方法。
    • @GSA 如果您正在寻找更多,请在您的问题中提供更多详细信息,否则我们将只能解决您发布的确切问题。
    • 我想要的是一种更通用的方式来将代码应用于两列以上而不单独列出每一列。
    • @GSA 如果您不列出它们并映射它们,代码如何知道哪个列应用什么功能??
    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 2013-02-22
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多