2017-01-23 55 views
1

我有一个熊猫(多指数)数据帧如下:降排在熊猫特定值GROUPBY

   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。然而我不知道如何仅在在帐户产品系列的开头删除零行。

如果有人能够帮助我,这将是伟大的!

回答

1

可以使用boolean indexing通过groupbycumsum创建mask和查找不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 
+0

谢谢!这工作很棒:) – Tessa