Skip to content

Show astype example with dict in docs #26990

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
stevennic opened this issue Jun 21, 2019 · 4 comments · Fixed by #26994
Closed

Show astype example with dict in docs #26990

stevennic opened this issue Jun 21, 2019 · 4 comments · Fixed by #26994
Labels

Comments

@stevennic
Copy link
Contributor

It would be useful to be able to change a column dtype inline.

For example with a DataFrame-level astype() overload:
Assuming df has a column called str_col that is a string (object),
df.astype(col='str_col', dtype='int').head()

The use case that brought me here is to numerically sort a string column without permanently changing it. What I was hoping to do is
df.astype(col='str_col', dtype='int').sort_values(by='str_col')

Instead, I had to do this:
df = df.assign(int_col = lambda x: x['str_col'].astype('int')).sort_values(by='int_col').drop('int_col', axis = 'columns')

The method would also support dictionaries for multiple column type changes:
df.astype({'col1':'type1', 'col2':'type2'})

@TomAugspurger
Copy link
Contributor

DataFrame.astype already accepts a dictionary of columns to dtypes, your last form. IMO, accepting **kwargs makes sense because it conflicts with other keyword arguments.

@stevennic
Copy link
Contributor Author

I hadn't noticed that! Thanks Tom. I see it in the documentation now, though perhaps it would be good to include at least one code example in the doc showing the dictionary form. I agree it's better to keep it in **kwargs even for one column to keep the method signature streamlined.

@WillAyd
Copy link
Member

WillAyd commented Jun 21, 2019

@stevennic improvements to documentation are almost always welcome. Would you like to make a PR?

@WillAyd WillAyd added the Docs label Jun 21, 2019
@WillAyd WillAyd changed the title Feature request: Inline astype() Show astype example with dict in docs Jun 21, 2019
@stevennic
Copy link
Contributor Author

Sure, that'll be my compensation for taking up resources here :)

stevennic added a commit to stevennic/pandas that referenced this issue Jun 22, 2019
stevennic added a commit to stevennic/pandas that referenced this issue Jun 22, 2019
TomAugspurger pushed a commit that referenced this issue Jun 22, 2019
* DOC: df.astype example using dictionary (#26990)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants