Skip to content

DataFrame.apply() does not retain category dtype if applied along axis 1 #23875

@JackCaster

Description

@JackCaster

Code Sample, a copy-pastable example if possible

import pandas as pd

def transform(s):
    return s

df = pd.DataFrame({'a':range(10), 'b':range(10)})

df['a'] = df['a'].astype('category')
print("(Before apply) df['a'] dtype is {}".format(df['a'].dtype)) # -> return category

df = df.apply(transform, axis=1)
print("(After apply) df['a'] dtype is {}".format(df['a'].dtype)) # -> return int64

Problem description

apply() does not retain the categorical dtype if applied on columns, but it does retain the dtype if applied on rows (set axis=0 in the snippet above).

Expected Output

The method should return a categorical dtype.

Output of pd.show_versions()

[paste the output of pd.show_versions() here below this line]

INSTALLED VERSIONS

commit: None
python: 3.6.7.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 69 Stepping 1, GenuineIntel
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: None.None

pandas: 0.23.4
pytest: None
pip: 18.1
setuptools: 40.5.0
Cython: None
numpy: 1.15.4
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 7.1.1
sphinx: None
patsy: 0.5.1
dateutil: 2.7.5
pytz: 2018.7
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 3.0.1
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: 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