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

Bug groupby quantile listlike q and int columns #30485

Merged
Show file tree
Hide file tree
Changes from 3 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.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,7 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrameGroupBy.agg` with timezone-aware datetime64 column incorrectly casting results to the original dtype (:issue:`29641`)
- Bug in :meth:`DataFrame.groupby` when using axis=1 and having a single level columns index (:issue:`30208`)
- Bug in :meth:`DataFrame.groupby` when using nunique on axis=1 (:issue:`30253`)
- Bug in :meth:`GroupBy.quantile` with multiple list-like q value and integer column names (:issue:`30289`)

Reshaping
^^^^^^^^^
Expand Down
25 changes: 13 additions & 12 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1937,21 +1937,22 @@ def post_processor(vals: np.ndarray, inference: Optional[Type]) -> np.ndarray:
# >>> result.stack(0).loc[pd.IndexSlice[:, ..., q], :]
# but this hits https://github.com/pandas-dev/pandas/issues/10710
# which doesn't reorder the list-like `q` on the inner level.
order = np.roll(list(range(result.index.nlevels)), -1)
result = result.reorder_levels(order)
result = result.reindex(q, level=-1)
order = list(range(1, result.index.nlevels)) + [0]

# temporarily saves the index names
index_names = np.array(result.index.names)
fujiaxiang marked this conversation as resolved.
Show resolved Hide resolved

# fix order.
hi = len(q) * self.ngroups
arr = np.arange(0, hi, self.ngroups)
arrays = []
# set index names to positions to avoid confusion
result.index.names = np.arange(len(index_names))

# place quantiles on the inside
result = result.reorder_levels(order)

for i in range(self.ngroups):
arr2 = arr + i
arrays.append(arr2)
# restore the index names in order
result.index.names = index_names[order]

indices = np.concatenate(arrays)
assert len(indices) == len(result)
# reorder rows to keep things sorted
indices = np.arange(len(result)).reshape([len(q), self.ngroups]).T.flatten()
jreback marked this conversation as resolved.
Show resolved Hide resolved
return result.take(indices)

@Substitution(name="groupby")
Expand Down
16 changes: 16 additions & 0 deletions pandas/tests/groupby/test_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -1398,6 +1398,22 @@ def test_quantile_array_multiple_levels():
tm.assert_frame_equal(result, expected)


def test_groupby_quantile_with_arraylike_q_and_int_columns():
fujiaxiang marked this conversation as resolved.
Show resolved Hide resolved
# GH30289
df = pd.DataFrame(np.array([2 * [_ % 4] for _ in range(10)]), columns=[0, 1])

quantiles = [0.5, 0.6]
expected_index = pd.MultiIndex.from_product(
[[0, 1, 2, 3], [0.5, 0.6]], names=[0, None]
)

expected_values = [float(x) for x in [0, 0, 1, 1, 2, 2, 3, 3]]
expected = pd.DataFrame(expected_values, index=expected_index, columns=[1])
result = df.groupby(0).quantile(quantiles)

tm.assert_frame_equal(result, expected)


def test_quantile_raises():
df = pd.DataFrame(
[["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"]
Expand Down