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

前端 未结 5 2068
名媛妹妹
名媛妹妹 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 22:18

    A quick and dirty solution would be something like this I imagine.

    You'd still have to add a condition to get the empty list, though.

    colors = df.colors.tolist()
    d = {}
    for l in colors:
        for c in l:
            if c not in d.keys():
                d.update({c: 1})
            else:
                current_val = d.get(c)
                d.update({c: current_val+1})
    

    this produces a dictionary looking like this:

    {'blue': 2, 'green': 2, 'brown': 2, 'red': 1, 'purple': 1}
    

提交回复
热议问题