Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop a group after groupby based on the presence of a value in a column in the group

On 0.24.1, given:

toy = pd.DataFrame({'g': [1,1,1,2,2,3,3], 'val': [0,2,3,4,5,6,0]})
toy
   g  val
0  1    0
1  1    2
2  1    3
3  2    4
4  2    5
5  3    6
6  3    0

I want to drop entire groups where the v column of the group contains a zero. In other words, after the incantation, which should preferably involve inplace=True to preserve my data transformation pipeline, I want toy to be:

   g  val
3  2    4
4  2    5
like image 448
Mike Avatar asked Dec 30 '25 03:12

Mike


1 Answers

Using filter

toy.groupby('g').filter(lambda x : all(x['val']!=0))
Out[58]: 
   g  val
3  2    4
4  2    5
like image 172
BENY Avatar answered Dec 31 '25 17:12

BENY