Skip to content

Conversation

fjetter
Copy link
Member

@fjetter fjetter commented Jul 30, 2025

Categorical codes are always copied by recode_for_categories regardless of the copy argument. This fixes it by passing the copy argument down to recode_for_categories

  • [ ] closes #xxxx (Replace xxxx with the GitHub issue number)
  • Tests added and passed if fixing a bug or adding a new feature
  • All code checks passed.
  • Added type annotations to new arguments/methods/functions.
  • Added an entry in the latest doc/source/whatsnew/vX.X.X.rst file if fixing a bug or adding a new feature.

@@ -575,7 +575,7 @@ def astype(self, dtype: AstypeArg, copy: bool = True) -> ArrayLike:
# GH 10696/18593/18630
dtype = self.dtype.update_dtype(dtype)
self = self.copy() if copy else self
Copy link
Member

Choose a reason for hiding this comment

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

Do we need this line if we pass self._set_dtype(dtype, copy=copy)?

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 wasn't entirely sure. The self.copy is also creating a new Categorical object which is desired, I assume.

@mroeschke mroeschke added the Categorical Categorical Data Type label Jul 30, 2025
@fjetter fjetter changed the title Avoid copying categoricals BUG: Avoid copying categorical codes if copy=False Jul 31, 2025
@fjetter fjetter marked this pull request as ready for review July 31, 2025 08:00
@mroeschke mroeschke added this to the 3.0 milestone Aug 1, 2025
@mroeschke mroeschke merged commit 9ff14a3 into pandas-dev:main Aug 1, 2025
43 checks passed
@mroeschke
Copy link
Member

Thanks @fjetter

@fjetter fjetter deleted the avoid_copy_categoricls branch August 4, 2025 07:05
eicchen pushed a commit to eicchen/pandas that referenced this pull request Aug 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Categorical Categorical Data Type
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants