How to assign a new level to many levels of a categorical variable I have a model which has many categorical variables. For each categorical variable there are many levels, like 50~. But not all of them have significant counts. I got these counts using the function value_counts() in Python:

A                 50 
B                 38
C                 26
D                 18
E                 10
...
T                 1
X                 1
Z                 1


How can I change the levels with count (say) less than 5 to a new level "others"?

for x in data.class:
    if x.value_counts() &lt;30:
        x = "others"
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)