Skip to content

Commit 5d67720

Browse files
pfrcksjorisvandenbossche
authored andcommitted
DOC: Added an example of pitfalls when using astype
- [x] closes #13260 - [ ] tests added / passed - [ ] passes ``git diff upstream/master | flake8 --diff`` - [ ] whatsnew entry Author: Amol <[email protected]> Closes #13278 from pfrcks/bug13260 and squashes the following commits: 035a177 [Amol] DOC: Final touches c30209d [Amol] DOC: Cleaning up 278e922 [Amol] DOC: Some cleaning up e1877bf [Amol] DOC: Restructured the documentation f394045 [Amol] DOC: Cleaned up the documentation 705e1a5 [Amol] DOC: Added an example of pitfalls when using astype
1 parent a67ac2a commit 5d67720

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

doc/source/basics.rst

+22
Original file line numberDiff line numberDiff line change
@@ -1726,6 +1726,28 @@ then the more *general* one will be used as the result of the operation.
17261726
# conversion of dtypes
17271727
df3.astype('float32').dtypes
17281728
1729+
Convert a subset of columns to a specified type using :meth:`~DataFrame.astype`
1730+
1731+
.. ipython:: python
1732+
1733+
dft = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
1734+
dft[['a','b']] = dft[['a','b']].astype(np.uint8)
1735+
dft
1736+
dft.dtypes
1737+
1738+
.. note::
1739+
1740+
When trying to convert a subset of columns to a specified type using :meth:`~DataFrame.astype` and :meth:`~DataFrame.loc`, upcasting occurs.
1741+
1742+
: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. Therefore the following piece of code produces the unintended result.
1743+
1744+
.. ipython:: python
1745+
1746+
dft = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
1747+
dft.loc[:, ['a', 'b']].astype(np.uint8).dtypes
1748+
dft.loc[:, ['a', 'b']] = dft.loc[:, ['a', 'b']].astype(np.uint8)
1749+
dft.dtypes
1750+
17291751
object conversion
17301752
~~~~~~~~~~~~~~~~~
17311753

0 commit comments

Comments
 (0)