Skip to content

HUH?: DataFrame[categorical].replace #33272

Closed
@jbrockmendel

Description

@jbrockmendel

When we have a DataFrame with 2 Categorical columns with matching dtypes and do a .replace on that DataFrame, the results do not match what we would get if we operate column-wise. Instead the results we get look like what we'd get if we stacked the columns, replaced, then unstacked.

i.e. AFAICT we are doing gymnastics to behave as if CategoricalBlock supported 2D Categorical.

From tests.frame.methods.test_replace:

replace_dict = {'a': 1, 'b': 2}
value = 3
df = pd.DataFrame([[1, 1], [2, 2]], columns=["a", "b"], dtype="category")

final_data = [[3, 1], [2, 3]]
expected = pd.DataFrame(final_data, columns=["a", "b"], dtype="category")
expected["a"] = expected["a"].cat.set_categories([1, 2, 3])
expected["b"] = expected["b"].cat.set_categories([1, 2, 3])

result = df.replace(replace_dict, value)
tm.assert_frame_equal(result, expected)

# this part is no longer from the test
col_wise = {col: df[col].replace(replace_dict[col], value) for col in df.columns}
result2 = pd.DataFrame(col_wise)

result2["a"].dtype
CategoricalDtype(categories=[3, 2], ordered=False)

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