Skip to content

BUG: wrong df.groupby().groups when grouping with [Grouper(freq=), ...] (GH33132) #33303

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 2 commits into from

Conversation

falcaopetri
Copy link

@falcaopetri
Copy link
Author

The proposed change breaks the equivalence of df.groupby(grouper) and df.groupby([grouper]), captured by test

def test_scalar_call_versus_list_call(self):

Currently executing this test results in:
(The correct behavior is the one in result, and not in expected.)

import pandas as pd
import pandas._testing as tm

data_frame = {
    "location": ["shanghai", "beijing", "shanghai"],
    "time": pd.Series(
        ["2017-08-09 13:32:23", "2017-08-11 23:23:15", "2017-08-11 22:23:15"],
        dtype="datetime64[ns]",
    ),
    "value": [1, 2, 3],
}
data_frame = pd.DataFrame(data_frame).set_index("time")
grouper = pd.Grouper(freq="D")

grouped = data_frame.groupby(grouper)
result = grouped.count()
grouped = data_frame.groupby([grouper])
expected = grouped.count()

print(result)
#             location  value
# time                       
# 2017-08-09         1      1
# 2017-08-10         0      0
# 2017-08-11         2      2
print(expected)
#             location  value
# time                       
# 2017-08-09         1      1
# 2017-08-11         2      2

The problem occurs when we have something like df.groupby([pd.Grouper(freq=)]) (i.e., a list with one element of type TimeGrouper).

One way to fix this is by capturing the keys arg in

class _GroupBy(PandasObject, SelectionMixin):
_group_selection = None
_apply_whitelist: FrozenSet[str] = frozenset()
def __init__(
self,
obj: NDFrame,
keys: Optional[_KeysArgType] = None,
and, if it is a [pd.Grouper], we transform it to a pd.Grouper.

Does this modification make sense?

@jreback
Copy link
Contributor

jreback commented Jun 14, 2020

please merge master and see if you can resolve the issues.

@mroeschke
Copy link
Member

Closing this PR as stale, but feel free to ping if you'd like to continue working on it.

@mroeschke mroeschke closed this Sep 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

BUG: wrong df.groupby().groups when grouping with [Grouper(freq=), ...]
3 participants