Skip to main content
 首页 » 编程设计

python之在 pandas groupby 中删除具有特定值的组开头的行

2024年10月17日11wayfarer

我有一个 Pandas (多索引)数据框如下:

             date       Volume 
Account ID                      
10001   2  02-03-2017   0 
        3  02-03-2017   0 
        3  09-03-2017   0 
        3  16-03-2017   50 
        3  21-03-2017   65 
        3  28-03-2017   0 
        3  04-04-2017   0 
        3  11-04-2017   60 
10002   5  02-03-2017   14.5 
        6  09-03-2017   14.5 
        3  09-03-2017   0 
        3  16-03-2017   0 
        3  21-03-2017   20 
        3  28-03-2017   33 
10003   8  21-03-2017   14.5 
        9  28-03-2017   15.0 

现在我想删除卷为 0 的系列(帐户-产品组合的日期)开始 处的所有行。所以我想保留卷为 0 的行,以防它们在系列的中间或结尾。

所以在上面的例子中,我想要以下输出:

             date       Volume 
Account ID                      
10001   3  16-03-2017   50 
        3  21-03-2017   65 
        3  28-03-2017   0 
        3  04-04-2017   0 
        3  11-04-2017   60 
10002   5  02-03-2017   14.5 
        6  09-03-2017   14.5 
        3  21-03-2017   20 
        3  28-03-2017   33 
10003   8  21-03-2017   14.5 
        9  28-03-2017   15.0 

目前,我一直在删除带有过滤器的完整系列,例如

df = data.groupby(level = acc_prod).filter(lambda x: len(x) > 26) 

而且我见过仅删除第一行的示例; Python: Pandas - Delete the first row by group .但是我不知道如何仅删除帐户产品系列开头的零行。

如果有人能帮我解决这个问题就太好了!

请您参考如下方法:

您可以使用 boolean indexing使用 mask 通过 groupby 创建 cumsum并找到不是 0 的值:

print (df.groupby(level=['Account','ID'])['Volume'].cumsum()) 
Account  ID 
10001    2       0.0 
         3       0.0 
         3       0.0 
         3      50.0 
         3     115.0 
         3     115.0 
         3     115.0 
         3     175.0 
10002    5      14.5 
         6      14.5 
         3       0.0 
         3       0.0 
         3      20.0 
         3      53.0 
10003    8      14.5 
         9      15.0 
Name: Volume, dtype: float64 
mask = df.groupby(level=['Account','ID'])['Volume'].cumsum() != 0 
#!= is same as ne function 
#mask = df.groupby(level=['Account','ID'])['Volume'].cumsum().ne(0) 
print (mask) 
Account  ID 
10001    2     False 
         3     False 
         3     False 
         3      True 
         3      True 
         3      True 
         3      True 
         3      True 
10002    5      True 
         6      True 
         3     False 
         3     False 
         3      True 
         3      True 
10003    8      True 
         9      True 
Name: Volume, dtype: bool 
print (df[mask]) 
                  date  Volume 
Account ID                     
10001   3   16-03-2017    50.0 
        3   21-03-2017    65.0 
        3   28-03-2017     0.0 
        3   04-04-2017     0.0 
        3   11-04-2017    60.0 
10002   5   02-03-2017    14.5 
        6   09-03-2017    14.5 
        3   21-03-2017    20.0 
        3   28-03-2017    33.0 
10003   8   21-03-2017    14.5 
        9   28-03-2017    15.0