def sort_by_code_and_level(parent_code_table, hierarchy):
    """ Sort by level order (not necessarily alphabetical). Uses merge-sort
    because it's stable i.e. won't mess with the original order of the entries
    if that matters. """
    parent_code_table.level = parent_code_table.level.astype(
        "category", categories=hierarchy
    )
    parent_code_table = parent_code_table.sort_values(
        ["level", "code"], kind="mergesort"
    ).reset_index(drop=True)
    parent_code_table.level = parent_code_table.level.astype("str")
    return parent_code_table