User 19826
User 19826

Reputation: 599

Pandas Apply Function - Syntax for row filtering

Similar to a previous question, I need to use the apply function to some data after using groupBy.

Suppose we have the following dataset with column heads A,B,C:

 a 0 2
 b 0 3
 c 0 4
 a 1 1
 b 1 2
 c 1 5
 a 0 3
 b 1 2
 c 0 1

and the following group by is applied:

   mydf=df.groupby(['A','B'])['C'].max()

I need to filter the group by result by a filter to show only those where C is 3, but get an error.

       print(mydf.apply(lambda g: g[g['C'] == 3]))

Thank you in advance.

Upvotes: 1

Views: 707

Answers (1)

anky
anky

Reputation: 75140

You can use .loc[] with a lambda here:

df.groupby(['A','B'])['C'].max().loc[lambda x: x==3]

A  B
a  0    3
b  0    3
Name: C, dtype: int64

Upvotes: 1

Related Questions