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

后端 未结 5 858
灰色年华
灰色年华 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:48

    Pandas DataFrame's merge and value_counts attributes are pretty fast, so I would combine the two.

    df.merge(df['brand'].value_counts().to_frame(), how='left', left_on='brand',
             right_index=True, suffixes=('', 'x'))\
      .rename(columns={'brandx':'brand_count'})
    

提交回复
热议问题