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

fix: expand all literals before group_by #11590

Merged
merged 1 commit into from
Oct 8, 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
13 changes: 9 additions & 4 deletions crates/polars-core/src/frame/group_by/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,21 @@ impl DataFrame {
!by.is_empty(),
ComputeError: "at least one key is required in a group_by operation"
);
let by_len = by[0].len();
let minimal_by_len = by.iter().map(|s| s.len()).min().expect("at least 1 key");
let df_height = self.height();

// we only throw this error if self.width > 0
// so that we can still call this on a dummy dataframe where we provide the keys
if (by_len != self.height()) && (self.width() > 0) {
if (minimal_by_len != df_height) && (self.width() > 0) {
polars_ensure!(
by_len == 1,
minimal_by_len == 1,
ShapeMismatch: "series used as keys should have the same length as the dataframe"
);
by[0] = by[0].new_from_index(0, self.height())
for by_key in by.iter_mut() {
if by_key.len() == minimal_by_len {
*by_key = by_key.new_from_index(0, df_height)
}
}
};

let n_partitions = _set_partition_size();
Expand Down
16 changes: 16 additions & 0 deletions py-polars/tests/unit/operations/test_group_by.py
Original file line number Diff line number Diff line change
Expand Up @@ -898,3 +898,19 @@ def test_groupby_dynamic_deprecated() -> None:
expected = df.group_by_dynamic("date", every="2d").agg(pl.sum("value"))
assert_frame_equal(result, expected, check_row_order=False)
assert_frame_equal(result_lazy, expected, check_row_order=False)


def test_group_by_multiple_keys_one_literal() -> None:
df = pl.DataFrame({"a": [1, 1, 2], "b": [4, 5, 6]})

expected = {"a": [1, 2], "literal": [1, 1], "b": [5, 6]}
for streaming in [True, False]:
assert (
df.lazy()
.group_by("a", pl.lit(1))
.agg(pl.col("b").max())
.sort(["a", "b"])
.collect(streaming=streaming)
.to_dict(False)
== expected
)