Skip to content

DOC: Added an example of pitfalls when using astype #13278

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
wants to merge 6 commits into from
Closed
Changes from 2 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
18 changes: 18 additions & 0 deletions doc/source/basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1726,6 +1726,24 @@ then the more *general* one will be used as the result of the operation.
# conversion of dtypes
df3.astype('float32').dtypes

When trying to convert a subset of columns to a specified type using :meth:`~DataFrame.astype` and :meth:`~DataFrame.loc`, utilizing **:** as mask, upcasting occurs.
:meth:`~DataFrame.loc` tries to fit in what we are assigning to the current dtypes, while [ ] will overwrite them taking the dtype from the right hand side.

.. ipython:: python

df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
Copy link
Contributor

Choose a reason for hiding this comment

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

call this dft or something besides df (as that's used a lot)

df.loc[:, ['a', 'b']].astype(np.uint8).dtypes
df.loc[:, ['a', 'b']] = df.loc[:, ['a', 'b']].astype(np.uint8)

To avoid this please take the following approach.

.. ipython:: python
Copy link
Member

Choose a reason for hiding this comment

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

Can you indent this one (and the following lines) to the same level as 'When trying to convert ...', so the code example is also included in the 'note' frame


Copy link
Contributor

Choose a reason for hiding this comment

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

flip these around showing the correct method of assignment using astype.

then you can put a ::note for the explanation. People reading this just want the answer; some want the explanation, so highliting that differently helps.

df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
Copy link
Contributor

Choose a reason for hiding this comment

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

you already created the df, no need to recreate

Copy link
Contributor Author

Choose a reason for hiding this comment

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

df get's changed in the code example before.

df[['a','b']] = df[['a','b']].astype(np.uint8)
df
df.dtypes

object conversion
~~~~~~~~~~~~~~~~~

Expand Down