Skip to content

BUG: Return DataFrame could not preserve index dtype when using .combine_first with categorical index #36568

@iascending

Description

@iascending
  • [ √] I have checked that this issue has not already been reported.

  • [√ ] I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.

Code Sample, a copy-pastable example

# Step1:  create 2 categorical series
x1 = pd.Categorical(['a', 'b', 'd'])
x2 = pd.Categorical(['a', 'b', 'c'])

# Step2: create `df` with multi index. Note here the multi index of
# df is `[x1, [1, 2, 3]]`
df = pd.DataFrame({'x': x1, 'a': [1, 2, 3], 'value': [55, 66, 77]})
df = df.set_index(['x', 'a'], drop=True)

# Step3: create a multi indexed series `s`. Note here the multi index
# of series `s` is `[x2, [1, 2, 3]]`. This multi index is different from 
# the multi index of `df`.
mi = pd.MultiIndex.from_arrays(
    [
        x2,
        [1, 2, 3]
    ],
    names=['x', 'a']
)
s = pd.Series([11, 22, 33], index=mi)

# Step4: Use combine_first to extend `df` with a new multi indexed series `s`
df2 = df.combine_first(pd.DataFrame({'some_col': s}))
df3 = df2.reset_index(drop=False)

# result comparison: 
# The `dtype` of level 0 index of original `df` is `CategoricalDtype` which
#  is what we we expected. `df2` is the return value of `combine_first`. 
# Its 'dtype' of level 0 index  is `dtype('O')` as shown below which is not 
# what we expected. We expect `df2` level 0 index `dtype` to be 
# `CategoricalDtype` too.
>>> df.index.get_level_values(0).dtype
CategoricalDtype(categories=['a', 'b', 'd'], ordered=False)
>>> df2.index.get_level_values(0).dtype
dtype('O')

Problem description

I use df.combine_first(...) to add a column to an existing dataframe while extending the index in case an index value does not exist in the target dataframe. One level of indexes is Categorical Dtype which came from df = df.set_index(['x', 'a'], drop=True) . I expected the Categorical dtype index could be restored by df3 = df2.reset_index(drop=False) after combine_first. However, if the MultIindex of the dataframe uses Categorical values in their index, the Categorical dtype info in the return dataframe lost .

Expected Output

df2 level 0 index hasCategoricalDtype

Output of pd.show_versions()

INSTALLED VERSIONS

commit : f2ca0a2
python : 3.8.3.final.0
python-bits : 64
OS : Darwin
OS-release : 19.6.0
Version : Darwin Kernel Version 19.6.0: Thu Jun 18 20:49:00 PDT 2020; root:xnu-6153.141.1~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_AU.UTF-8
LOCALE : en_AU.UTF-8

pandas : 1.1.1
numpy : 1.18.4
pytz : 2019.3
dateutil : 2.8.1
pip : 20.2.3
setuptools : 47.3.1
Cython : 0.29.17
pytest : 5.1.1
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 0.9.6
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.8.3 (dt dec pq3 ext lo64)
jinja2 : 2.11.2
IPython : 7.16.1
pandas_datareader: None
bs4 : None
bottleneck : 1.3.1
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.2.2
numexpr : 2.7.1
odfpy : None
openpyxl : 1.8.6
pandas_gbq : None
pyarrow : 0.17.1
pytables : None
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : 1.3.12
tables : 3.6.1
tabulate : None
xarray : None
xlrd : 1.2.0
xlwt : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions