How to assign a new level to many levels of a categorical variable
Say your data is in a DataFrame df, and the column of interest is named column.

treshold = 5 #or whatever value makes sense to you

def set_levels(df):

    for i df.column.unique():
       if len(df.loc[df.column == i]) &lt; treshold:
          df.loc[df.column == i] = 'other'

    return df

new_df = set_levels(df)