Skip to content

REF: simplify Grouping.__init__ #41528

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

Merged
merged 1 commit into from
May 18, 2021
Merged
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
46 changes: 23 additions & 23 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,34 +500,33 @@ def __init__(
# use Index instead of ndarray so we can recover the name
self.grouper = Index(ng, name=newgrouper.result_index.name)

else:
elif is_categorical_dtype(self.grouper):
# a passed Categorical
if is_categorical_dtype(self.grouper):
self._passed_categorical = True
self._passed_categorical = True

self.grouper, self.all_grouper = recode_for_groupby(
self.grouper, self.sort, observed
)
self.grouper, self.all_grouper = recode_for_groupby(
self.grouper, self.sort, observed
)

elif not isinstance(self.grouper, (Series, Index, ExtensionArray, np.ndarray)):
# no level passed
elif not isinstance(
self.grouper, (Series, Index, ExtensionArray, np.ndarray)
if getattr(self.grouper, "ndim", 1) != 1:
t = self.name or str(type(self.grouper))
raise ValueError(f"Grouper for '{t}' not 1-dimensional")

self.grouper = self.index.map(self.grouper)

if not (
hasattr(self.grouper, "__len__")
and len(self.grouper) == len(self.index)
):
if getattr(self.grouper, "ndim", 1) != 1:
t = self.name or str(type(self.grouper))
raise ValueError(f"Grouper for '{t}' not 1-dimensional")
self.grouper = self.index.map(self.grouper)
if not (
hasattr(self.grouper, "__len__")
and len(self.grouper) == len(self.index)
):
grper = pprint_thing(self.grouper)
errmsg = (
"Grouper result violates len(labels) == "
f"len(data)\nresult: {grper}"
)
self.grouper = None # Try for sanity
raise AssertionError(errmsg)
grper = pprint_thing(self.grouper)
errmsg = (
"Grouper result violates len(labels) == "
f"len(data)\nresult: {grper}"
)
self.grouper = None # Try for sanity
raise AssertionError(errmsg)
Copy link
Contributor

Choose a reason for hiding this comment

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

OT is this ever hit in tests? we should not be raising an AssertionError


if isinstance(self.grouper, np.ndarray):
# if we have a date/time-like grouper, make sure that we have
Expand Down Expand Up @@ -555,6 +554,7 @@ def name(self) -> Hashable:
elif isinstance(self.grouper, Index):
return self.grouper.name

# otherwise we have ndarray or ExtensionArray -> no name
return None

@cache_readonly
Expand Down