Reputation: 6485
I have a dataframe and I'd like to groupby a field and then select only values which is not zero as my aggregate function and then convert them into a list. Here is the code I have
df.sort_values(by='col1').groupby('col2').apply(lambda x: x if x!=0).apply(list)
However if says invalid syntax
. What am I doing wrong?
Upvotes: 2
Views: 246
Reputation: 403050
Turn the first function to apply
into a lambda
and do the filtering there:
(df.sort_values(by='col1')
.groupby('col2')
.apply(lambda x: [y for y in x if y != 0]))
Upvotes: 1