Q:

Merging pandas categorical Series with renaming

I am looking for a way to merge categories of one object of pandas.Series to categories of another.
import pandas as pd
from pandas import Series, Categorical

N = Series(["a","b","c","a"], dtype="category", name = "NEW_TEST")
N1 = N.copy()
N2 = N.copy()

Works
N1.cat.categories = ['AA', 'BB', 'CC']

Throws error ValueError: Categorical categories must be unique
N2.cat.categories = ['AA', 'AA', 'CC'] 

I would like to rename-merge categories. Thus all values from category b will end-up in category AA.

A:

One way of doing this is just to assign the category to all elements in the series of the category you want to rename:
In [59]: N
Out[59]:
0    a
1    b
2    c
3    a
Name: NEW_TEST, dtype: category
Categories (3, object): [a < b < c]

In [60]: N[N=='b'] = 'a'

In [61]: N
Out[61]:
0    a
1    a
2    c
3    a
Name: NEW_TEST, dtype: category
Categories (3, object): [a < b < c]

Now, all elements with category 'b' are assigned with category 'a'. If you now remove category 'b', this will end up with a 'merge' in practice:
In [62]: N.cat.remove_unused_categories()
Out[62]:
0    a
1    a
2    c
3    a
dtype: category
Categories (2, object): [a < c]

In [63]: N.cat.remove_categories(['b'])
Out[63]:
0    a
1    a
2    c
3    a
dtype: category
Categories (2, object): [a < c]

