Skip to content
Advertisement

How to groupby multiple columns with count unique value in Python Pandas

I have a DataFrame df_data:

JavaScript

I have a function and parameter like this:

JavaScript

Explain Parameters: with CustID = 1 the parameters should be list_minor = [3,1] (position is not important), list_major = [1] because with LocationID = 324 he get 3 times and LocationID = 490 he get 1 time (324,490 gets isMajor = 0 so it should be into 1 list). Similiar, CustID2 have parameters list_minor = [1] and list_major = [] (if he don’t have data major/minor, I should be pass [].

This is my program:

JavaScript

But results of df_parameter['parameters'] is wrong:

JavaScript

Can I get the parameters I explained above with groupby and pass them to the function?

Advertisement

Answer

How about:

JavaScript

Output:

JavaScript

Update Try this one groupby:

JavaScript

Also, groupby with two keys can be slow. In that case, you can just concatenate the keys and groupby on that:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement