-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Added
Table.group_by
to group a table by a given key (#343)
Closes #160. ### Summary of Changes Added a `group_by` method for the table class that requires a lambda function which computes the grouping keys. The method returns a dictionary with the computed keys as keys and the grouped rows as new Tables as values. --------- Co-authored-by: Alexander Gréus <[email protected]> Co-authored-by: megalinter-bot <[email protected]> Co-authored-by: alex-senger <[email protected]>
- Loading branch information
1 parent
9a332b2
commit afb98be
Showing
2 changed files
with
62 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
tests/safeds/data/tabular/containers/_table/test_group_by.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from collections.abc import Callable | ||
|
||
import pytest | ||
from safeds.data.tabular.containers import Table | ||
|
||
|
||
@pytest.mark.parametrize( | ||
("table", "selector", "expected"), | ||
[ | ||
( | ||
Table({"col1": [1, 1, 2, 2, 3], "col2": ["a", "b", "c", "d", "e"]}), | ||
lambda row: row["col1"], | ||
{ | ||
1: Table({"col1": [1, 1], "col2": ["a", "b"]}), | ||
2: Table({"col1": [2, 2], "col2": ["c", "d"]}), | ||
3: Table({"col1": [3], "col2": ["e"]}), | ||
}, | ||
), | ||
( | ||
Table({"col1": [1, 1, 2, 2, 3], "col2": ["a", "b", "c", "d", 2]}), | ||
lambda row: row["col1"], | ||
{ | ||
1: Table({"col1": [1, 1], "col2": ["a", "b"]}), | ||
2: Table({"col1": [2, 2], "col2": ["c", "d"]}), | ||
3: Table({"col1": [3], "col2": [2]}), | ||
}, | ||
), | ||
(Table(), lambda row: row["col1"], {}), | ||
(Table({"col1": [], "col2": []}), lambda row: row["col1"], {}), | ||
], | ||
ids=["select by row1", "different types in column", "empty table", "table with no rows"], | ||
) | ||
def test_group_by(table: Table, selector: Callable, expected: dict) -> None: | ||
out = table.group_by(selector) | ||
assert out == expected |