Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python using ternary operator in groupby

Is there a way to use the ternary operator inside a groupby condition?Apparently this syntax is invalid.

d = {'name':['bil','bil','bil','jim'],
     'col2': ['acct','law', 'acct2','law'],
     'col3': [1,2,3,55],
     'col4': [1,1,1,2]

    }
df2 = pd.DataFrame(data=d)

df2[['col4']] = df2[['col4']].apply(pd.to_numeric)
df2.groupby(['name','col2'])['col4']\
    .max() if (.max()>30) else ''
like image 683
Rilcon42 Avatar asked Apr 07 '26 03:04

Rilcon42


1 Answers

You can use a ternary, but I'm not going to show you that. Instead, here's a better alternative - mask the result:

v = df2.groupby(['name','col2'])['col4'].max()
v.where(v.gt(30), '')

Using lambdas inside groupby slows its operation down quite drastically.

like image 104
cs95 Avatar answered Apr 09 '26 16:04

cs95