Skip to content

BUG: pd.concat doesn't preserve categorical dtypes #51362

Open
@YarShev

Description

@YarShev

Pandas version checks

  • I have checked that this issue has not already been reported.

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

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

df = pd.DataFrame({"a": [0, 1]})
df2 = pd.DataFrame({"a": [2, 3]})

print(df.dtypes)
# a    int64
# dtype: object
print(df2.dtypes)
# a    int64
# dtype: object

df3 = pd.concat([df, df2], axis=0)
print(df3.dtypes)
# a    int64
# dtype: object

df = df.astype('category')
df2 = df2.astype('category')

print(df.dtypes)
# a    category
# dtype: object
print(df2.dtypes)
# a    category
# dtype: object

df3 = pd.concat([df, df2], axis=0)
print(df3.dtypes)
a    int64
dtype: object

Issue Description

pd.concat doesn't preserve categorical dtype if the dfs have categorical columns, whereas pd.concat preserves int dtype.

Expected Behavior

The result dtype should be categorical, shouldn't it?

Installed Versions

pandas : 1.5.3
numpy : 1.24.1
pytz : 2022.7.1
dateutil : 2.8.2
setuptools : 66.1.1
pip : 22.3.1
Cython : None
pytest : 7.2.1
hypothesis : None
sphinx : 6.1.3
blosc : None
feather : 0.4.1
xlsxwriter : None
lxml.etree : 4.9.2
html5lib : None
pymysql : None
psycopg2 : 2.9.3
jinja2 : 3.1.2
IPython : 8.8.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli :
fastparquet : 2022.12.0
fsspec : 2023.1.0
gcsfs : None
matplotlib : 3.6.3
numba : None
numexpr : 2.8.3
odfpy : None
openpyxl : 3.0.10
pandas_gbq : 0.15.0
pyarrow : 10.0.1
pyreadstat : None
pyxlsb : None
s3fs : 2023.1.0
scipy : 1.10.0
snappy : None
sqlalchemy : 1.4.46
tables : 3.7.0
tabulate : None
xarray : 2023.1.0
xlrd : 2.0.1
xlwt : None
zstandard : None
tzdata : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugCategoricalCategorical Data TypeReshapingConcat, Merge/Join, Stack/Unstack, Explode

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions