diff --git a/src/safeds/data/tabular/containers/_column.py b/src/safeds/data/tabular/containers/_column.py index 3851ac291..52704edf8 100644 --- a/src/safeds/data/tabular/containers/_column.py +++ b/src/safeds/data/tabular/containers/_column.py @@ -24,6 +24,7 @@ from collections.abc import Callable, Iterator T = TypeVar("T") +R = TypeVar("R") class Column(Sequence[T]): @@ -300,6 +301,8 @@ def rename(self, new_name: str) -> Column: """ Return a new column with a new name. + This column is not modified. + Parameters ---------- new_name : str @@ -312,6 +315,30 @@ def rename(self, new_name: str) -> Column: """ return Column._from_pandas_series(self._data.rename(new_name), self._type) + def transform(self, transformer: Callable[[T], R]) -> Column[R]: + """ + Apply a transform method to every data point. + + This column is not modified. + + Parameters + ---------- + transformer : Callable[[T], R] + Function that will be applied to all data points. + + Returns + ------- + transformed_column: Column + The transformed column. + + Examples + -------- + >>> from safeds.data.tabular.containers import Column + >>> price = Column("price", [4.99, 5.99, 2.49]) + >>> sale = price.transform(lambda amount: amount * 0.8) + """ + return Column(self.name, self._data.apply(transformer, convert_dtype=True)) + # ------------------------------------------------------------------------------------------------------------------ # Statistics # ------------------------------------------------------------------------------------------------------------------ diff --git a/tests/safeds/data/tabular/containers/_column/test_transform.py b/tests/safeds/data/tabular/containers/_column/test_transform.py new file mode 100644 index 000000000..8e35ab2c0 --- /dev/null +++ b/tests/safeds/data/tabular/containers/_column/test_transform.py @@ -0,0 +1,29 @@ +import pytest +from safeds.data.tabular.containers import Column + + +@pytest.mark.parametrize( + ("column", "expected"), + [ + (Column("test", []), Column("test", [])), + (Column("test", [1, 2]), Column("test", [2, 3])), + (Column("test", [-0.5, 0, 4]), Column("test", [0.5, 1, 5])), + ], + ids=["empty", "integers", "floats"], +) +def test_should_transform_column(column: Column, expected: Column) -> None: + assert column.transform(lambda it: it + 1) == expected + + +@pytest.mark.parametrize( + ("column", "original"), + [ + (Column("test", []), Column("test", [])), + (Column("test", [1, 2]), Column("test", [1, 2])), + (Column("test", [-0.5, 0, 4]), Column("test", [-0.5, 0, 4])), + ], + ids=["empty", "integers", "floats"], +) +def test_should_not_change_original_column(column: Column, original: Column) -> None: + column.transform(lambda it: it + 1) + assert column == original