Skip to content

ENH: .astype() with dictionary while preserving type(self) #45676

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
sambo55 opened this issue Jan 28, 2022 · 1 comment
Closed

ENH: .astype() with dictionary while preserving type(self) #45676

sambo55 opened this issue Jan 28, 2022 · 1 comment
Labels
Astype Duplicate Report Duplicate issue or pull request Enhancement Subclassing Subclassing pandas objects

Comments

@sambo55
Copy link

sambo55 commented Jan 28, 2022

Is your feature request related to a problem?

[this should provide a description of what the problem is, e.g. "I wish I could use pandas to do [...]"]

I have a custom DataFrame class with

class CustomFrame(DataFrame):
@property
    def _constructor(self):
        return CustomFrame

which allows me to use normal pandas methods and preserves my custom DataFrame object.

When using df.astype({'col':'type'}) the type returned is always a DataFrame instead of preserving the self._constructor and returning a CustomFrame

When using df.assign(col = col.astype('type')) the type returned is CustomFrame

Describe the solution you'd like

If we could change

result = result.__finalize__(self, method="astype")

to

result = self._constructor(results).__finalize__(self, method="astype")

then the constructor call would ensure the correct type is returned which is what is used in the col.astype('type') case
self._constructor(new_data).__finalize__(self, method="astype")

API breaking implications

I don't think this would break anything, the resulting objects in both cases are the same except for the type.

Describe alternatives you've considered

I could just use the assign pattern as a workaround but it would be nice if we could also use the dictionary notation

Additional context

# Your code here, if applicable
@sambo55 sambo55 added Enhancement Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 28, 2022
@phofl
Copy link
Member

phofl commented Jan 28, 2022

Duplicate of #40810

@phofl phofl marked this as a duplicate of #40810 Jan 28, 2022
@phofl phofl closed this as completed Jan 28, 2022
@phofl phofl added Astype Duplicate Report Duplicate issue or pull request Subclassing Subclassing pandas objects and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 28, 2022
@phofl phofl added this to the No action milestone Jan 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Astype Duplicate Report Duplicate issue or pull request Enhancement Subclassing Subclassing pandas objects
Projects
None yet
Development

No branches or pull requests

2 participants