def recode_for_groupby(c, sort, observed):
    if observed:
        unique_codes = unique1d(c.codes)
        take_codes = unique_codes[unique_codes != -1]
        if c.ordered:
            take_codes = np.sort(take_codes)
        categories = c.categories.take(take_codes)
        codes = _recode_for_categories(c.codes,
                                       c.categories,
                                       categories)
        dtype = CategoricalDtype(categories, ordered=c.ordered)
        return Categorical(codes, dtype=dtype, fastpath=True), c
    if sort:
        return c, None
    cat = c.unique()
    cat = cat.add_categories(
        c.categories[~c.categories.isin(cat.categories)])
    return c.reorder_categories(cat.categories), None