From e9c7f29646fa1b1b206eef95e5c7c7403c27227e Mon Sep 17 00:00:00 2001 From: topper-123 Date: Wed, 9 Aug 2017 12:24:36 +0100 Subject: [PATCH] DOC: Updated NDFrame.astype docs (#17203) --- pandas/core/generic.py | 50 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2d52eed81d22b..bd3297f66a469 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3610,8 +3610,7 @@ def blocks(self): mapping={True: 'raise', False: 'ignore'}) def astype(self, dtype, copy=True, errors='raise', **kwargs): """ - Cast object to input numpy.dtype - Return a copy when copy = True (be really careful with this!) + Cast a pandas object to a specified dtype ``dtype``. Parameters ---------- @@ -3620,6 +3619,10 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs): the same type. Alternatively, use {col: dtype, ...}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame's columns to column-specific types. + copy : bool, default True. + Return a copy when ``copy=True`` (be very careful setting + ``copy=False`` as changes to values then may propagate to other + pandas objects). errors : {'raise', 'ignore'}, default 'raise'. Control raising of exceptions on invalid data for provided dtype. @@ -3636,6 +3639,49 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs): Returns ------- casted : type of caller + + Examples + -------- + >>> ser = pd.Series([1, 2], dtype='int32') + >>> ser + 0 1 + 1 2 + dtype: int32 + >>> ser.astype('int64') + 0 1 + 1 2 + dtype: int64 + + Convert to categorical type: + + >>> ser.astype('category') + 0 1 + 1 2 + dtype: category + Categories (2, int64): [1, 2] + + Convert to ordered categorical type with custom ordering: + + >>> ser.astype('category', ordered=True, categories=[2, 1]) + 0 1 + 1 2 + dtype: category + Categories (2, int64): [2 < 1] + + Note that using ``copy=False`` and changing data on a new + pandas object may propagate changes: + + >>> s1 = pd.Series([1,2]) + >>> s2 = s1.astype('int', copy=False) + >>> s2[0] = 10 + >>> s1 # note that s1[0] has changed too + 0 10 + 1 2 + dtype: int64 + + See also + -------- + numpy.ndarray.astype : Cast a numpy array to a specified type. """ if is_dict_like(dtype): if self.ndim == 1: # i.e. Series