【问题标题】:How do you specify pandas groupby operations that operate on previous records?您如何指定对先前记录进行操作的 pandas groupby 操作?
【发布时间】:2018-05-30 16:00:54
【问题描述】:

我有一个 Pandas 数据框如下,它必须按 Col_2 排序:

+----+-------+-------+ 
| id | Col_1 | Col_2 |
+----+-------+-------+
|  1 |     0 |    21 |
|  1 |     1 |    24 |
|  1 |     1 |    32 |
|  1 |     0 |    35 |
|  1 |     1 |    37 |
|  2 |     0 |     2 |
|  2 |     0 |     5 |
+----+-------+-------+

如何创建两个新列:

Col_1_sum:每个 id 的前几行中的值的总和。 Col_2_max:Col_2 在 Col_1 为 1 的最后几行中的最大值。 (对于每个 id)

例如对于上面的数据框,结果应该是:

+----+-------+-------+-----------+-----------+
| id | Col_1 | Col_2 | Col_1_Sum | Col_2_Max |
+----+-------+-------+-----------+-----------+
|  1 |     0 |    21 |         0 |         0 |
|  1 |     1 |    24 |         0 |         0 |
|  1 |     1 |    32 |         1 |        24 |
|  1 |     0 |    35 |         2 |        32 |
|  1 |     1 |    37 |         2 |        32 |
|  2 |     0 |     2 |         0 |         0 |
|  2 |     0 |     5 |         0 |         0 |
+----+-------+-------+-----------+-----------+

【问题讨论】:

    标签: python pandas dataframe group-by pandas-groupby


    【解决方案1】:

    你有两个问题。一次一个。

    groupbyshiftcumsum 回答了您的第一个问题:

    df.groupby('id').Col_1.apply(lambda x: x.shift().cumsum())
    
    0    NaN
    1    0.0
    2    1.0
    3    2.0
    4    2.0
    5    NaN
    6    0.0
    Name: Col_1, dtype: float64
    

    或者,如果您更喜欢更简洁的输出,

    df.groupby('id').Col_1.apply(lambda x: x.shift().cumsum()).fillna(0).astype(int)
    
    0    0
    1    0
    2    1
    3    2
    4    2
    5    0
    6    0
    Name: Col_1, dtype: int64
    

    您的第二个,也类似,使用groupbyshiftcummaxffill

    df.Col_2.where(df.Col_1.eq(1)).groupby(df.id).apply(
        lambda x: x.shift().cummax().ffill()
    )
    
    0     NaN
    1     NaN
    2    24.0
    3    32.0
    4    32.0
    5     NaN
    6     NaN
    Name: Col_2, dtype: float64
    

    在这两种情况下,基本要素是groupby,然后是随后的轮班电话。请注意,这些答案很难在没有apply 的情况下解决,因为要对子组执行多项操作。

    考虑通过定义一个自定义函数来取出 lambda。您将在更大的数据上节省几个周期。

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 2018-02-01
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多