[Python] Pandas groupby with tag-style list

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataset with 'tag-like' groupings:

    Id tags
    0 item1 ['friends','family']
    1 item2 ['friends']
    2 item3 []
    3 item4 ['family','holiday']


    So a row can belong to several groups. I want to create an object similar to groupby, so that I can use agg etc.

    df.groupby('tags').count()


    expected result

    tags count
    0 'friends' 2
    1 'family' 2
    2 'holiday' 1


    But of course it won't work because it treats the whole list as the key, rather than the individual tags. Here's an attempt

    tagset = set(df.tags.explode())
    grpby = { t: df.loc[df.tags.str.contains(t, regex=False)]
    for t in tagset }


    From what I understand, groupby objects are structured a bit like this. But how to make it a groupby object? So that I can do things like grpby.year.mean() etc?

    Continue reading...

Compartilhe esta Página