代码之家  ›  专栏  ›  技术社区  ›  JejeBelfort Ted Petrou

将函数应用于特定行的范围

  •  1
  • JejeBelfort Ted Petrou  · 技术社区  · 5 年前

    我有以下数据框 df :

                bucket_value  is_new_bucket
    dates                                  
    2019-03-07             0              1
    2019-03-08             1              0
    2019-03-09             2              0
    2019-03-10             3              0
    2019-03-11             4              0
    2019-03-12             5              1
    2019-03-13             6              0
    2019-03-14             7              1
    

    我想对每个 bucket_value 列所在的数据组 is_new_bucket 等于零,因此生成的数据帧如下所示:

                mean_values
    dates             
    2019-03-08     2.5
    2019-03-13     6.0
    

    换句话说,将一个函数应用于 is_new_bucket = 0 ,这需要 桶值 作为输入。

    例如,如果我想应用max函数,生成的数据帧将如下所示:

                max_values
    dates             
    2019-03-11     4.0
    2019-03-13     6.0
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   BENY    5 年前

    使用 cumsum 具有 filter

    df.reset_index(inplace=True)
    s=df.loc[df.is_new_bucket==0].groupby(df.is_new_bucket.cumsum()).agg({'date':'first','bucket_value':['mean','max']})
    s
                        date bucket_value    
                       first         mean max
    is_new_bucket                            
    1             2019-03-08          2.5   4
    2             2019-03-13          6.0   6
    

    更新的

    df.loc[df.loc[df.is_new_bucket==0].groupby(df.is_new_bucket.cumsum())['bucket_value'].idxmax()]
            date  bucket_value  is_new_bucket
    4 2019-03-11             4              0
    6 2019-03-13             6              0
    

    使用后更新了2 累加 创建组密钥newkey,您可以根据组密钥执行任何需要的操作

    df['Newkey']=df.is_new_bucket.cumsum()
    df
            date  bucket_value  is_new_bucket  Newkey
    0 2019-03-07             0              1       1
    1 2019-03-08             1              0       1
    2 2019-03-09             2              0       1
    3 2019-03-10             3              0       1
    4 2019-03-11             4              0       1
    5 2019-03-12             5              1       2
    6 2019-03-13             6              0       2
    7 2019-03-14             7              1       3