Skip to content

Commit 556effc

Browse files
topper-123jorisvandenbossche
authored andcommitted
DOC: Updated NDFrame.astype docs (#17203)
1 parent 3e9e947 commit 556effc

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

pandas/core/generic.py

+48-2
Original file line numberDiff line numberDiff line change
@@ -3610,8 +3610,7 @@ def blocks(self):
36103610
mapping={True: 'raise', False: 'ignore'})
36113611
def astype(self, dtype, copy=True, errors='raise', **kwargs):
36123612
"""
3613-
Cast object to input numpy.dtype
3614-
Return a copy when copy = True (be really careful with this!)
3613+
Cast a pandas object to a specified dtype ``dtype``.
36153614
36163615
Parameters
36173616
----------
@@ -3620,6 +3619,10 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs):
36203619
the same type. Alternatively, use {col: dtype, ...}, where col is a
36213620
column label and dtype is a numpy.dtype or Python type to cast one
36223621
or more of the DataFrame's columns to column-specific types.
3622+
copy : bool, default True.
3623+
Return a copy when ``copy=True`` (be very careful setting
3624+
``copy=False`` as changes to values then may propagate to other
3625+
pandas objects).
36233626
errors : {'raise', 'ignore'}, default 'raise'.
36243627
Control raising of exceptions on invalid data for provided dtype.
36253628
@@ -3636,6 +3639,49 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs):
36363639
Returns
36373640
-------
36383641
casted : type of caller
3642+
3643+
Examples
3644+
--------
3645+
>>> ser = pd.Series([1, 2], dtype='int32')
3646+
>>> ser
3647+
0 1
3648+
1 2
3649+
dtype: int32
3650+
>>> ser.astype('int64')
3651+
0 1
3652+
1 2
3653+
dtype: int64
3654+
3655+
Convert to categorical type:
3656+
3657+
>>> ser.astype('category')
3658+
0 1
3659+
1 2
3660+
dtype: category
3661+
Categories (2, int64): [1, 2]
3662+
3663+
Convert to ordered categorical type with custom ordering:
3664+
3665+
>>> ser.astype('category', ordered=True, categories=[2, 1])
3666+
0 1
3667+
1 2
3668+
dtype: category
3669+
Categories (2, int64): [2 < 1]
3670+
3671+
Note that using ``copy=False`` and changing data on a new
3672+
pandas object may propagate changes:
3673+
3674+
>>> s1 = pd.Series([1,2])
3675+
>>> s2 = s1.astype('int', copy=False)
3676+
>>> s2[0] = 10
3677+
>>> s1 # note that s1[0] has changed too
3678+
0 10
3679+
1 2
3680+
dtype: int64
3681+
3682+
See also
3683+
--------
3684+
numpy.ndarray.astype : Cast a numpy array to a specified type.
36393685
"""
36403686
if is_dict_like(dtype):
36413687
if self.ndim == 1: # i.e. Series

0 commit comments

Comments
 (0)