【问题标题】:Apply a function to each column of groupby对 groupby 的每一列应用一个函数
【发布时间】:2021-09-23 14:56:22
【问题描述】:

假设我有一个数据框 df,它有两个索引级别,如下所示:

     col 1  col 2
A 1      1      5
  2      2      3
B 1      2      4
  2      1      4

现在我想通过some_function 为每个级别 0 索引的每一列计算一个值。所以对于每一组:

groups = df.groupby(level = 0)

不幸的是,我的some_function 在我的情况下只接受一维数据。我找到了一种方法来做到这一点,但我对我的解决方案并不满意,因为我不知道如何将它应用于大数据帧,而且感觉很多余。

df_new=groups.aggregate({"col 1":some_function,"col 2":some_function"})

有没有更好的方法来获得相同的结果?

【问题讨论】:

  • 试试applygroups.apply(lambda g: g.apply(some_function))
  • 我认为groups.agg(some_function) 应该适用于每列
  • 小技巧。如果您不确定传递给您的函数的内容,请使用print 进行测试。例如df.agg(print) 将逐列打印列,这确认传递的数据是一维(系列)。

标签: python pandas group-by multi-index


【解决方案1】:

使用stackgroupby

df.stack().groupby(level=[0, 2]).apply(some_function)

例子:

>>> df
     col 1  col 2
A 1      1      5
  2      2      3
B 1      2      4
  2      1      4

>>> df.stack()
A  1  col 1    1
      col 2    5
   2  col 1    2
      col 2    3
B  1  col 1    2
      col 2    4
   2  col 1    1
      col 2    4
dtype: int64

>>> list(df.stack().groupby(level=[0, 2]))
[(('A', 'col 1'),  # <- first group
  A  1  col 1    1
     2  col 1    2
  dtype: int64),
 (('A', 'col 2'),  # <- second group
  A  1  col 2    5
     2  col 2    3
  dtype: int64),
 (('B', 'col 1'),  # <- third group
  B  1  col 1    2
     2  col 1    1
  dtype: int64),
 (('B', 'col 2'),  # <- fourth group
  B  1  col 2    4
     2  col 2    4
  dtype: int64)]

【讨论】:

    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2011-06-15
    • 2017-01-20
    相关资源
    最近更新 更多