Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve DataFrame.column subclass and type during binop #18113

Open
wants to merge 6 commits into
base: branch-25.04
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 20 additions & 14 deletions python/cudf/cudf/core/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -2055,15 +2055,14 @@ def _make_operands_and_index_for_binop(
dict[str | None, tuple[ColumnBase, Any, bool, Any]]
| NotImplementedType,
BaseIndex | None,
bool,
dict[str, Any],
]:
lhs, rhs = self._data, other
index = self.index
fill_requires_key = False
left_default: Any = False
equal_columns = False
can_use_self_column_name = True

ca_attributes: dict[str, Any] = {}
if _is_scalar_or_zero_d_array(other):
rhs = {name: other for name in self._data}
equal_columns = True
Expand All @@ -2085,9 +2084,13 @@ def _make_operands_and_index_for_binop(
# NULL!) and the right value (result is NaN).
left_default = as_column(np.nan, length=len(self))
equal_columns = other_pd_index.equals(self_pd_columns)
can_use_self_column_name = (
equal_columns or other_pd_index.names == self_pd_columns.names
)
if equal_columns:
ca_attributes["rangeindex"] = self._data.rangeindex
ca_attributes["multiindex"] = self._data.multiindex
ca_attributes["label_dtype"] = self._data.label_dtype
ca_attributes["level_names"] = self._data.level_names
elif other_pd_index.names == self_pd_columns.names:
ca_attributes["level_names"] = self._data.level_names
elif isinstance(other, DataFrame):
if (
not can_reindex
Expand All @@ -2110,17 +2113,20 @@ def _make_operands_and_index_for_binop(
# the fill value.
left_default = fill_value
equal_columns = self._column_names == other._column_names
can_use_self_column_name = (
equal_columns
or self._data._level_names == other._data._level_names
)
if self._data.to_pandas_index.equals(other._data.to_pandas_index):
ca_attributes["rangeindex"] = self._data.rangeindex
ca_attributes["multiindex"] = self._data.multiindex
ca_attributes["label_dtype"] = self._data.label_dtype
ca_attributes["level_names"] = self._data.level_names
elif self._data._level_names == other._data._level_names:
ca_attributes["level_names"] = self._data.level_names
elif isinstance(other, (dict, abc.Mapping)):
# Need to fail early on host mapping types because we ultimately
# convert everything to a dict.
return NotImplemented, None, True
return NotImplemented, None, ca_attributes

if not isinstance(rhs, (dict, abc.Mapping)):
return NotImplemented, None, True
return NotImplemented, None, ca_attributes

operands = {
k: (
Expand Down Expand Up @@ -2150,8 +2156,8 @@ def _make_operands_and_index_for_binop(
raise ValueError("other must be a DataFrame or Series.")

sorted_dict = {key: operands[key] for key in column_names_list}
return sorted_dict, index, can_use_self_column_name
return operands, index, can_use_self_column_name
return sorted_dict, index, ca_attributes
return operands, index, ca_attributes

@classmethod
@_performance_tracking
Expand Down
10 changes: 3 additions & 7 deletions python/cudf/cudf/core/indexed_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4888,20 +4888,16 @@ def _binaryop(
(
operands,
out_index,
can_use_self_column_name,
ca_attributes,
) = self._make_operands_and_index_for_binop(
other, op, fill_value, reflect, can_reindex
)
if operands is NotImplemented:
return NotImplemented

level_names = (
self._data._level_names if can_use_self_column_name else None
)
return self._from_data(
ColumnAccessor(
type(self)._colwise_binop(operands, op),
level_names=level_names,
**ca_attributes,
),
index=out_index,
)
Expand All @@ -4917,7 +4913,7 @@ def _make_operands_and_index_for_binop(
dict[str | None, tuple[ColumnBase, Any, bool, Any]]
| NotImplementedType,
cudf.BaseIndex | None,
bool,
dict[str, Any],
]:
raise NotImplementedError(
f"Binary operations are not supported for {self.__class__}"
Expand Down
15 changes: 7 additions & 8 deletions python/cudf/cudf/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1531,7 +1531,7 @@ def _make_operands_and_index_for_binop(
dict[str | None, tuple[ColumnBase, Any, bool, Any]]
| NotImplementedType,
BaseIndex | None,
bool,
dict[str, Any],
]:
# Specialize binops to align indices.
if isinstance(other, Series):
Expand All @@ -1547,15 +1547,14 @@ def _make_operands_and_index_for_binop(
else:
lhs = self

try:
can_use_self_column_name = cudf.utils.utils._is_same_name(
self.name, other.name
)
except AttributeError:
can_use_self_column_name = False
ca_attributes = {}
if hasattr(other, "name") and cudf.utils.utils._is_same_name(
self.name, other.name
):
ca_attributes["level_names"] = self._data._level_names

operands = lhs._make_operands_for_binop(other, fill_value, reflect)
return operands, lhs.index, can_use_self_column_name
return operands, lhs.index, ca_attributes

@copy_docstring(CategoricalAccessor) # type: ignore
@property
Expand Down
14 changes: 14 additions & 0 deletions python/cudf/cudf/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -11083,6 +11083,20 @@ def test_dataframe_columns_set_preserve_type(klass):
pd.testing.assert_index_equal(result, expected)


@pytest.mark.parametrize(
"expected",
[
pd.RangeIndex(1, 2, name="a"),
pd.Index([1], dtype=np.int8, name="a"),
pd.MultiIndex.from_arrays([[1]], names=["a"]),
],
)
def test_dataframe_binop_preserves_column_metadata(expected):
df = cudf.DataFrame([1], columns=expected)
result = (df == df).columns
pd.testing.assert_index_equal(result, expected, exact=True)


@pytest.mark.parametrize(
"scalar",
[
Expand Down
Loading