Skip to content

fix: Improve Series.replace for dict input #907

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

Merged
merged 4 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 7 additions & 1 deletion bigframes/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,9 @@ def _simple_replace(self, to_replace_list: typing.Sequence, value):
return Series(block.select_column(result_col))

def _mapping_replace(self, mapping: dict[typing.Hashable, typing.Hashable]):
if not mapping:
return self.copy()

tuples = []
lcd_types: list[typing.Optional[bigframes.dtypes.Dtype]] = []
for key, value in mapping.items():
Expand All @@ -597,6 +600,7 @@ def _mapping_replace(self, mapping: dict[typing.Hashable, typing.Hashable]):
result_dtype = functools.reduce(
lambda t1, t2: bigframes.dtypes.lcd_type(t1, t2) if (t1 and t2) else None,
lcd_types,
self.dtype,
)
if not result_dtype:
raise NotImplementedError(
Expand All @@ -605,7 +609,9 @@ def _mapping_replace(self, mapping: dict[typing.Hashable, typing.Hashable]):
block, result = self._block.apply_unary_op(
self._value_column, ops.MapOp(tuple(tuples))
)
return Series(block.select_column(result))
replaced = Series(block.select_column(result))
replaced.name = self.name
return replaced

@validations.requires_ordering()
@validations.requires_index
Expand Down
23 changes: 23 additions & 0 deletions tests/system/small/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,29 @@ def test_series_replace_list_scalar(scalars_dfs):
)


@pytest.mark.parametrize(
("replacement_dict",),
(
({"Hello, World!": "Howdy, Planet!", "T": "R"},),
({},),
),
ids=[
"non-empty",
"empty",
],
)
def test_series_replace_dict(scalars_dfs, replacement_dict):
scalars_df, scalars_pandas_df = scalars_dfs
col_name = "string_col"
bf_result = scalars_df[col_name].replace(replacement_dict).to_pandas()
pd_result = scalars_pandas_df[col_name].replace(replacement_dict)

pd.testing.assert_series_equal(
pd_result,
bf_result,
)


@pytest.mark.parametrize(
("method",),
(
Expand Down