Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop groups in groupby that do not contain an element (Python Pandas)

Tags:

python

pandas

Let a data frame be like the following:

import pandas as pd

df = pd.DataFrame({"name":["A", "A", "B" ,"B", "C", "C"],
                   "nickname":["X","Y","X","Z","Y", "Y"]}

How can I group df and drop those groups (C) that do not contain at least one 'X'?

thank you

like image 247
dleal Avatar asked Dec 10 '22 16:12

dleal


1 Answers

You can use the grouped by filter from pandas:

df.groupby('name').filter(lambda g: any(g.nickname == 'X')) 

#       name   nickname
# 0        A          X
# 1        A          Y
# 2        B          X
# 3        B          Z
like image 198
Psidom Avatar answered Jun 05 '23 07:06

Psidom