Reset the index of a Series or DataFrame
| 2373 | |
| 2374 | |
| 2375 | class ResetIndex(Elemwise): |
| 2376 | """Reset the index of a Series or DataFrame""" |
| 2377 | |
| 2378 | _parameters = ["frame", "drop", "name"] |
| 2379 | _defaults = {"drop": False, "name": no_default} |
| 2380 | _keyword_only = ["drop", "name"] |
| 2381 | operation = M.reset_index |
| 2382 | _filter_passthrough = True |
| 2383 | _preserves_partitioning_information = True |
| 2384 | |
| 2385 | @functools.cached_property |
| 2386 | def _kwargs(self) -> dict: |
| 2387 | kwargs = {"drop": self.drop} |
| 2388 | if self.operand("name") is not no_default: |
| 2389 | kwargs.update({"name": self.operand("name")}) |
| 2390 | return kwargs |
| 2391 | |
| 2392 | def _divisions(self): |
| 2393 | return (None,) * (self.frame.npartitions + 1) |
| 2394 | |
| 2395 | def _simplify_up(self, parent, dependents): |
| 2396 | if isinstance(parent, Filter) and self._filter_passthrough_available( |
| 2397 | parent, dependents |
| 2398 | ): |
| 2399 | parents = [ |
| 2400 | p().columns |
| 2401 | for p in dependents[self._name] |
| 2402 | if p() is not None and not isinstance(p(), Filter) |
| 2403 | ] |
| 2404 | predicate = None |
| 2405 | if not set(flatten(parents, list)).issubset(set(self.frame.columns)): |
| 2406 | # one of the filters is the Index |
| 2407 | name = self.operand("name") or self.frame._meta.index.name |
| 2408 | if name is no_default and self.frame._meta.index.name is None: |
| 2409 | name = "index" |
| 2410 | elif self.frame._meta.index.name is not None: |
| 2411 | name = self.frame._meta.index.name |
| 2412 | # replace the projection of the former index with the actual index |
| 2413 | subs = Projection(self, name) |
| 2414 | predicate = parent.predicate.substitute(subs, Index(self.frame)) |
| 2415 | elif self.frame.ndim == 1 and not self.operand("drop"): |
| 2416 | name = self.frame._meta.name |
| 2417 | # Avoid Projection since we are already a Series |
| 2418 | subs = Projection(self, name) |
| 2419 | predicate = parent.predicate.substitute(subs, self.frame) |
| 2420 | return self._filter_simplification(parent, predicate) |
| 2421 | |
| 2422 | if isinstance(parent, Projection): |
| 2423 | if self.frame.ndim == 1 and not self.drop: |
| 2424 | if isinstance(parent.operand("columns"), list): |
| 2425 | # Don't bother, dimensionality changes are tricky here and |
| 2426 | # potential improvement is tiny |
| 2427 | return |
| 2428 | col = parent.operand("columns") |
| 2429 | if col in (self.name, "index", self.frame._meta.index.name): |
| 2430 | return |
| 2431 | if all( |
| 2432 | isinstance(d(), Projection) and d().operand("columns") == col |