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

前端 未结 5 2075
名媛妹妹
名媛妹妹 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:04

    I would use .apply with pd.Series to accomplish this:

    # 1. Expand columns and count them
    df_temp = df["colors"].apply(pd.Series.value_counts)
    
        blue    brown   green   purple  red
    0   1.0 1.0 1.0 NaN NaN
    1   NaN NaN NaN NaN NaN
    2   1.0 NaN 1.0 NaN 1.0
    3   NaN NaN NaN 1.0 NaN
    4   NaN 1.0 NaN NaN NaN
    
    # 2. Get the value counts from this:
    df_temp.sum()
    
    blue      2.0
    brown     2.0
    green     2.0
    purple    1.0
    red       1.0
    
    # Alternatively, convert to a dict
    df_temp.sum().to_dict()
    # {'blue': 2.0, 'brown': 2.0, 'green': 2.0, 'purple': 1.0, 'red': 1.0}
    

提交回复
热议问题