How to use different combinations of group by while trying to get the top most viewed

前端 未结 3 2156
遇见更好的自我
遇见更好的自我 2021-01-26 13:30

Am trying to get the top most rating using groupby of multiple columns and if there is no combination of that particular groupby, its throwing me an error . how to do multiple c

3条回答
  •  清歌不尽
    2021-01-26 14:05

    This is one non-pandas solution. Counter.most_common() orders results by most common descending counts.

    from collections import Counter
    
    def get_top(maritalstatus=None, gender=None, age_range=None, occ=None):
    
        cols = ['maritalstatus', 'gender', 'age_range', 'occ']
        values = [maritalstatus, gender, age_range, occ]
    
        c = Counter(df.query(' & '.join((('({0} ==  "{1}")').format(i, j)) \
                    for i, j in zip(cols, values) if j))['rating'])
    
        return c.most_common()
    
    get_top(maritalstatus='ma', gender='M', age_range='young')  # [('PG', 2)]
    

提交回复
热议问题