Skip to content

BUG: Debug grouped quantile with NA values #33571

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

Closed
wants to merge 8 commits into from
Closed
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`)
- Bug in :meth:`DataFrame.resample` where an ``AmbiguousTimeError`` would be raised when the resulting timezone aware :class:`DatetimeIndex` had a DST transition at midnight (:issue:`25758`)
- Bug in :meth:`DataFrame.groupby` where a ``ValueError`` would be raised when grouping by a categorical column with read-only categories and ``sort=False`` (:issue:`33410`)
- Bug in :meth:`DataFrameGroupBy.quantile` where incorrect values would be returned when missing group keys were present (:issue:`33569`)
- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)

Reshaping
Expand Down
11 changes: 8 additions & 3 deletions pandas/_libs/groupby.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -778,9 +778,14 @@ def group_quantile(ndarray[float64_t] out,
if not mask[i]:
non_na_counts[lab] += 1

# Get an index of values sorted by labels and then values
order = (values, labels)
sort_arr = np.lexsort(order).astype(np.int64, copy=False)
# Get an index of values sorted by labels and then values,
# make sure missing labels sort to the back of the array
if labels.size:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the subsequent loop even account for missing labels in iteration? If not I wonder if cleaner to just remove rather than force sorting this way

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I think we'd also have to remove from values so that the two have the same shape for lexsort (that might break what's below but I'm not sure honestly)

labels_for_lexsort = np.where(labels == -1, labels.max() + 1, labels)
else:
labels_for_lexsort = labels

sort_arr = np.lexsort((values, labels_for_lexsort)).astype(np.int64, copy=False)

with nogil:
for i in range(ngroups):
Expand Down
23 changes: 17 additions & 6 deletions pandas/tests/groupby/test_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -1507,14 +1507,25 @@ def test_quantile_missing_group_values_no_segfaults():
grp.quantile()


def test_quantile_missing_group_values_correct_results():
@pytest.mark.parametrize(
"key",
[
["a"] * 4 + ["b"] * 3 + [np.nan],
["a"] * 3 + [np.nan] + ["b"] * 4,
["a"] * 3 + [np.nan] + ["b"] * 3 + [np.nan],
],
)
@pytest.mark.parametrize(
"quantile, expected_value", [(0.0, 1.0), (0.5, 2.0), (1.0, 3.0)]
)
def test_quantile_missing_group_values_correct_results(key, quantile, expected_value):
# GH 28662
data = np.array([1.0, np.nan, 3.0, np.nan])
df = pd.DataFrame(dict(key=data, val=range(4)))

result = df.groupby("key").quantile()
# https://github.com/pandas-dev/pandas/issues/33569
value = np.array([1.0, 2.0, 3.0, np.nan] * 2)
df = pd.DataFrame({"key": key, "value": value})
result = df.groupby("key").quantile(quantile)
expected = pd.DataFrame(
[1.0, 3.0], index=pd.Index([1.0, 3.0], name="key"), columns=["val"]
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty sure this test was wrong, the values for the non-null labels are 0 and 2, so these quantiles don't make sense

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[expected_value] * 2, index=pd.Index(["a", "b"], name="key"), columns=["value"]
)
tm.assert_frame_equal(result, expected)

Expand Down