Skip to content

Columns lose category dtype after calling replace on the dataframe #23305

Closed
@somiandras

Description

@somiandras

xref #25521

Code Sample, a copy-pastable example if possible

>>> import pandas as pd
>>> pd.__version__
'0.23.4'

# Sample dataframe with two categorical and one int column
>>> df = pd.DataFrame(
...     [[1., 'A', 'x'], [2, 'B', 'y'], [3, 'C', 'z']],
...     columns=['first', 'second', 'third']
... ).astype({'second': 'category', 'third': 'category'})

# Replace int values
>>> df = df.replace(1, 10)

# Both categorical columns turned into object...
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
first     3 non-null float64
second    3 non-null object
third     3 non-null object
dtypes: float64(1), object(2)
memory usage: 152.0+ bytes

# Sample dataframe with two categorical columns
>>> df = pd.DataFrame(
...     [['A', 'x'], ['B', 'y'], ['C', 'z']],
...     columns=['first', 'second',]
... ).astype({'first': 'category', 'second': 'category'})

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
first     3 non-null category
second    3 non-null category
dtypes: category(2)
memory usage: 294.0 bytes

# Replace values in column `first`
>>> df = df.replace('A', 'B')

# Dtype of column `second` becomes object
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
first     3 non-null category
second    3 non-null object
dtypes: category(1), object(1)
memory usage: 211.0+ bytes

Problem description

Calling replace() on a dataframe changes category columns' dtype to object in an apparently inconsisent manner:

  1. When replace() contains non-categorical values that are not present in either categorical column, all categorical dtype turn into object.
  2. When replace() contains categories from a category dtype column, then that column keeps its dtype, but other categorical columns turn into object.

See the examples above for both. Even if it is somehow intentional I find it quite confusing.

Expected Output

I would expect the categorical columns to keep their category dtype after replace is called on the dataframe (at least for those categorical columns that are unaffected by replace).

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None

pandas: 0.23.4
pytest: None
pip: 18.0
setuptools: 39.0.1
Cython: None
numpy: 1.15.0
scipy: 1.1.0
pyarrow: None
xarray: None
IPython: 6.5.0
sphinx: None
patsy: None
dateutil: 2.7.3
pytz: 2018.5
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: 2.2.3
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: 1.0.1
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

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions