How to merge pandas value_counts() to dataframe or use it to subset a dataframe

后端 未结 5 861
灰色年华
灰色年华 2021-02-05 23:53

I used pandas df.value_counts() to find the number of occurrences of particular brands. I want to merge those value counts with the respective brands in the initial dataframe.

5条回答
  •  余生分开走
    2021-02-06 00:33

    df = ...
    key_col = "brand"
    count_col = "brand_count"
    
    result = (
        df.join(
            df[key_col].value_counts().rename(count_col), 
            how="left", 
            on=key_col)
    )
    

    If you need to join the counts to a different dataframe remember to fill NaNs with zeros:

    df = ...
    other = ...
    key_col = "brand"
    count_col = "brand_count"
    
    result = (
        other.join(
            df[key_col].value_counts().rename(count_col), 
            how="left", 
            on=key_col)
        .fillna({count_col: 0})
    )
    

提交回复
热议问题