Skip to content

Commit 705e1a5

Browse files
committed
DOC: Added an example of pitfalls when using astype
1 parent 4e4a7d9 commit 705e1a5

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

doc/source/basics.rst

+17
Original file line numberDiff line numberDiff line change
@@ -1726,6 +1726,23 @@ 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+
When trying to convert a subset of columns to a specified type using :meth:`~DataFrame.astype` and :meth:`~numpy.ndarray.loc`, utilizing **:** as mask, upcasting occurs.
1730+
:meth:`~numpy.ndarray.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.
1731+
1732+
.. ipython:: python
1733+
1734+
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
1735+
print df.loc[:, ['a', 'b']].astype(np.uint8).dtypes
1736+
df.loc[:, ['a', 'b']] = df.loc[:, ['a', 'b']].astype(np.uint8)
1737+
1738+
To avoid this please take the following approach.
1739+
1740+
.. ipython:: python
1741+
1742+
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
1743+
df[['a','b']] = df[['a','b']].astype(np.uint8)
1744+
df
1745+
df.dtypes
17291746
object conversion
17301747
~~~~~~~~~~~~~~~~~
17311748

0 commit comments

Comments
 (0)