I have a pandas data frame with a factor column with 30 different levels. Some of the levels occur infrequently so I convert them to an 'Other' grouping. The resulting column has 25 different levels plus 1 'other' level.
d = df1['column1'].value_counts() >= 50
df1['column1'] = [i if d[i] else 'Other' for i in df1['column1']]
df1['column1'] = df1['column1'].astype('category')
I have a second data frame that I'd like to convert to have the same levels as the first data frame (including any new levels that don't occur in the first data frame). I've tried the code below but I get a 'Key Error' but it doesn't really explain the issue.
df2['column1'] = [i if d[i] else 'Other' for i in df2['column1']]
df2['column1'] = df2['column1'].astype('category')
Any idea what's causing this?