diff --git a/doc/source/api/series.rst b/doc/source/api/series.rst index 7d5e6037b012a..8e4c378b9fefe 100644 --- a/doc/source/api/series.rst +++ b/doc/source/api/series.rst @@ -26,6 +26,7 @@ Attributes .. autosummary:: :toctree: generated/ + Series.array Series.values Series.dtype Series.ftype @@ -58,10 +59,12 @@ Conversion Series.convert_objects Series.copy Series.bool + Series.to_numpy Series.to_period Series.to_timestamp Series.to_list Series.get_values + Series.__array__ Indexing, iteration ------------------- diff --git a/pandas/core/series.py b/pandas/core/series.py index 3128e67f86873..f416e638b9176 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -662,12 +662,53 @@ def view(self, dtype=None): # ---------------------------------------------------------------------- # NDArray Compat - def __array__(self, result=None): + def __array__(self, dtype=None): """ - The array interface, return my values. + Return the values as a NumPy array. + + Users should not call this directly. Rather, it is invoked by + :func:`numpy.array` and :func:`numpy.asarray`. + + Parameters + ---------- + dtype : str or numpy.dtype, optional + The dtype to use for the resulting NumPy array. By default, + the dtype is inferred from the data. + + Returns + ------- + numpy.ndarray + The values in the series converted to a :class:`numpy.ndarary` + with the specified `dtype`. + + See Also + -------- + Series.array : Zero-copy view to the array backing the Series. + Series.to_numpy : Series method for similar behavior. + + Examples + -------- + >>> ser = pd.Series([1, 2, 3]) + >>> np.asarray(ser) + array([1, 2, 3]) + + For timezone-aware data, the timezones may be retained with + ``dtype='object'`` + + >>> tzser = pd.Series(pd.date_range('2000', periods=2, tz="CET")) + >>> np.asarray(tzser, dtype="object") + array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'), + Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')], + dtype=object) + + Or the values may be localized to UTC and the tzinfo discared with + ``dtype='datetime64[ns]'`` + + >>> np.asarray(tzser, dtype="datetime64[ns]") # doctest: +ELLIPSIS + array(['1999-12-31T23:00:00.000000000', ...], + dtype='datetime64[ns]') """ - # TODO: change the keyword name from result to dtype? - if (result is None and isinstance(self.array, ABCDatetimeArray) + if (dtype is None and isinstance(self.array, ABCDatetimeArray) and getattr(self.dtype, 'tz', None)): msg = ( "Converting timezone-aware DatetimeArray to timezone-naive " @@ -678,8 +719,8 @@ def __array__(self, result=None): "To keep the old behavior, pass 'dtype=\"datetime64[ns]\"'." ) warnings.warn(msg, FutureWarning, stacklevel=3) - result = 'M8[ns]' - return np.asarray(self.array, result) + dtype = 'M8[ns]' + return np.asarray(self.array, dtype) def __array_wrap__(self, result, context=None): """