How do I count the values from a pandas column which is a list of strings?

前端 未结 5 2055
名媛妹妹
名媛妹妹 2021-01-19 21:53

I have a dataframe column which is a list of strings:

df[\'colors\']

0              [\'blue\',\'green\',\'brown\']
1              []
2              [\'green\         


        
5条回答
  •  天命终不由人
    2021-01-19 21:58

    You can use Counter from the collections module:

    import pandas as pd
    from collections import Counter
    from  itertools import chain
    
    df = pd.DataFrame({'colors':[['blue','green','brown'],
                                 [],
                                 ['green','red','blue'],
                                 ['purple'],
                                 ['brown']]})
    
    df = pd.Series(Counter(chain(*df.colors)))
    
    print (df)
    

    Output:

    blue      2
    green     2
    brown     2
    red       1
    purple    1
    dtype: int64
    

提交回复
热议问题