'Other' category for values appearing less than 5 times

Viewed 55

job_title has too many different values for it to be useful so I am trying to create an 'other' category for all values in job_title that have occurred less than 5 times.

I have managed to display those that occur less than 5 times through the code below:

df[df.groupby('job_title')['job_title'].transform('size') < 5]

This is far as I have got but I need to be able to label all of these under the same category of 'other' I'm wondering if anyone can help.

1 Answers

Let's use loc to assign values, based on this boolean series.

df.loc[df.groupby('job_title')['job_title'].transform('size')<5, 'job_title'] = 'Other'
Related