Get unique values from pandas series of lists

后端 未结 1 589
难免孤独
难免孤独 2021-02-04 09:40

I have a column in DataFrame containing list of categories. For example:

0                                                    [Pizza]
1                                   


        
相关标签:
1条回答
  • 2021-02-04 10:09

    Update using pandas 0.25.0+ with explode

    df['category'].explode().value_counts()
    

    Output:

    Barbeque       3
    Mexican        3
    Fusion         2
    Thai           2
    American       2
    Bars           2
    Asian          2
    Hawaiian       1
    New            1
    Brunch         1
    Pizza          1
    Traditional    1
    Pubs           1
    Korean         1
    Pakistani      1
    Burgers        1
    Diners         1
    Indian         1
    Desserts       1
    Halal          1
    Nightlife      1
    Breakfast      1
    Name: Places, dtype: int64
    

    And with plotting:

    df['category'].explode().value_counts().plot.pie(figsize=(8,8))
    

    Output:


    For older verions of pandas before 0.25.0 Try:

    df['category'].apply(pd.Series).stack().value_counts()
    

    Output:

    Mexican        3
    Barbeque       3
    Thai           2
    Fusion         2
    American       2
    Bars           2
    Asian          2
    Pubs           1
    Burgers        1
    Traditional    1
    Brunch         1
    Indian         1
    Korean         1
    Halal          1
    Pakistani      1
    Hawaiian       1
    Diners         1
    Pizza          1
    Nightlife      1
    New            1
    Desserts       1
    Breakfast      1
    dtype: int64
    

    With plotting:

    df['category'].apply(pd.Series).stack().value_counts().plot.pie()
    

    Output:

    Per @coldspeed's comments

    from itertools import chain
    from collections import Counter
    
    pd.DataFrame.from_dict(Counter(chain(*df['category'])), orient='index').sort_values(0, ascending=False)
    

    Output:

    Barbeque     3
    Mexican      3
    Bars         2
    American     2
    Thai         2
    Asian        2
    Fusion       2
    Pizza        1
    Diners       1
    Halal        1
    Pakistani    1
    Brunch       1
    Breakfast    1
    Burgers      1
    Hawaiian     1
    Traditional  1
    Pubs         1
    Korean       1
    Desserts     1
    New          1
    Nightlife    1
    Indian       1
    
    0 讨论(0)
提交回复
热议问题