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

Support callables in DataFrame.assign #14142

Merged
merged 2 commits into from
Sep 22, 2023
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
23 changes: 14 additions & 9 deletions python/cudf/cudf/core/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -1390,10 +1390,21 @@ def _get_numeric_data(self):
return self[columns]

@_cudf_nvtx_annotate
def assign(self, **kwargs):
def assign(self, **kwargs: Union[Callable[[Self], Any], Any]):
"""
Assign columns to DataFrame from keyword arguments.

Parameters
----------
**kwargs: dict mapping string column names to values
The value for each key can either be a literal column (or
something that can be converted to a column), or
a callable of one argument that will be given the
dataframe as an argument and should return the new column
(without modifying the input argument).
Columns are added in-order, so callables can refer to
column names constructed in the assignment.

Examples
--------
>>> import cudf
Expand All @@ -1405,15 +1416,9 @@ def assign(self, **kwargs):
1 1 4
2 2 5
"""
new_df = cudf.DataFrame(index=self.index.copy())
for name, col in self._data.items():
if name in kwargs:
new_df[name] = kwargs.pop(name)
else:
new_df._data[name] = col.copy()

new_df = self.copy(deep=False)
for k, v in kwargs.items():
new_df[k] = v
new_df[k] = v(new_df) if callable(v) else v
return new_df

@classmethod
Expand Down
19 changes: 19 additions & 0 deletions python/cudf/cudf/tests/test_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -1327,6 +1327,25 @@ def test_assign():
np.testing.assert_equal(gdf2.y.to_numpy(), [2, 3, 4])


@pytest.mark.parametrize(
"mapping",
[
{"y": 1, "z": lambda df: df["x"] + df["y"]},
{
"x": lambda df: df["x"] * 2,
"y": lambda df: 2,
"z": lambda df: df["x"] / df["y"],
},
],
)
def test_assign_callable(mapping):
df = pd.DataFrame({"x": [1, 2, 3]})
cdf = cudf.from_pandas(df)
expect = df.assign(**mapping)
actual = cdf.assign(**mapping)
assert_eq(expect, actual)


@pytest.mark.parametrize("nrows", [1, 8, 100, 1000])
@pytest.mark.parametrize("method", ["murmur3", "md5"])
@pytest.mark.parametrize("seed", [None, 42])
Expand Down