Skip to content

Commit

Permalink
DEPR: deprecate .asobject property (#18572)
Browse files Browse the repository at this point in the history
  • Loading branch information
topper-123 authored and jorisvandenbossche committed Dec 4, 2017
1 parent 6e56195 commit aa5b6e6
Show file tree
Hide file tree
Showing 32 changed files with 158 additions and 127 deletions.
2 changes: 1 addition & 1 deletion asv_bench/benchmarks/index_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def setup(self):
if (self.rng.dtype == object):
self.idx_rng = self.rng.view(Index)
else:
self.idx_rng = self.rng.asobject
self.idx_rng = self.rng.astype(object)
self.idx_rng2 = self.idx_rng[:(-1)]

# other datetime
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.22.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ Deprecations

- ``Series.from_array`` and ``SparseSeries.from_array`` are deprecated. Use the normal constructor ``Series(..)`` and ``SparseSeries(..)`` instead (:issue:`18213`).
- ``DataFrame.as_matrix`` is deprecated. Use ``DataFrame.values`` instead (:issue:`18458`).
-
- ``Series.asobject``, ``DatetimeIndex.asobject``, ``PeriodIndex.asobject`` and ``TimeDeltaIndex.asobject`` have been deprecated. Use '.astype(object)' instead (:issue:`18572`)

.. _whatsnew_0220.prior_deprecations:

Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/algos_common_helper.pxi.in
Original file line number Diff line number Diff line change
Expand Up @@ -552,8 +552,8 @@ cpdef ensure_object(object arr):
return arr
else:
return arr.astype(np.object_)
elif hasattr(arr, 'asobject'):
return arr.asobject
elif hasattr(arr, '_box_values_as_index'):
return arr._box_values_as_index()
else:
return np.array(arr, dtype=np.object_)

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class DirNamesMixin(object):
_accessors = frozenset([])
_deprecations = frozenset([])
_deprecations = frozenset(['asobject'])

def _dir_deletions(self):
""" delete unwanted __dir__ for this object """
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ def unique(values):
# to return an object array of tz-aware Timestamps

# TODO: it must return DatetimeArray with tz in pandas 2.0
uniques = uniques.asobject.values
uniques = uniques.astype(object).values

return uniques

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/dtypes/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ def convert_to_pydatetime(x, axis):
# if dtype is of datetimetz or timezone
if x.dtype.kind == _NS_DTYPE.kind:
if getattr(x, 'tz', None) is not None:
x = x.asobject.values
x = x.astype(object).values
else:
shape = x.shape
x = tslib.ints_to_pydatetime(x.view(np.int64).ravel(),
Expand Down Expand Up @@ -479,7 +479,7 @@ def _concat_index_asobject(to_concat, name=None):
"""

klasses = ABCDatetimeIndex, ABCTimedeltaIndex, ABCPeriodIndex
to_concat = [x.asobject if isinstance(x, klasses) else x
to_concat = [x.astype(object) if isinstance(x, klasses) else x
for x in to_concat]

from pandas import Index
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3330,7 +3330,7 @@ class max type

def _maybe_casted_values(index, labels=None):
if isinstance(index, PeriodIndex):
values = index.asobject.values
values = index.astype(object).values
elif isinstance(index, DatetimeIndex) and index.tz is not None:
values = index
else:
Expand Down Expand Up @@ -5077,7 +5077,7 @@ def applymap(self, func):
def infer(x):
if x.empty:
return lib.map_infer(x, func)
return lib.map_infer(x.asobject, func)
return lib.map_infer(x.astype(object).values, func)

return self.apply(infer)

Expand Down
21 changes: 15 additions & 6 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,13 @@ def _box_values(self, values):
"""
return lib.map_infer(values, self._box_func)

def _box_values_as_index(self):
"""
return object Index which contains boxed values
"""
from pandas.core.index import Index
return Index(self._box_values(self.asi8), name=self.name, dtype=object)

def _format_with_header(self, header, **kwargs):
return header + list(self._format_native_types(**kwargs))

Expand Down Expand Up @@ -360,7 +367,7 @@ def map(self, f):
raise TypeError('The map function must return an Index object')
return result
except Exception:
return self.asobject.map(f)
return self.astype(object).map(f)

def sort_values(self, return_indexer=False, ascending=True):
"""
Expand Down Expand Up @@ -424,13 +431,15 @@ def _isnan(self):

@property
def asobject(self):
"""
"""DEPRECATED: Use ``astype(object)`` instead.
return object Index which contains boxed values
*this is an internal non-public method*
"""
from pandas.core.index import Index
return Index(self._box_values(self.asi8), name=self.name, dtype=object)
warnings.warn("'asobject' is deprecated. Use 'astype(object)'"
" instead", FutureWarning, stacklevel=2)
return self.astype(object)

def _convert_tolerance(self, tolerance, target):
tolerance = np.asarray(to_timedelta(tolerance, box=False))
Expand Down Expand Up @@ -468,7 +477,7 @@ def tolist(self):
"""
return a list of the underlying data
"""
return list(self.asobject)
return list(self.astype(object))

def min(self, axis=None, *args, **kwargs):
"""
Expand Down Expand Up @@ -746,7 +755,7 @@ def isin(self, values):
try:
values = type(self)(values)
except ValueError:
return self.asobject.isin(values)
return self.astype(object).isin(values)

return algorithms.isin(self.asi8, values.asi8)

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -907,7 +907,7 @@ def to_datetime(self, dayfirst=False):
def astype(self, dtype, copy=True):
dtype = pandas_dtype(dtype)
if is_object_dtype(dtype):
return self.asobject
return self._box_values_as_index()
elif is_integer_dtype(dtype):
return Index(self.values.astype('i8', copy=copy), name=self.name,
dtype='i8')
Expand Down Expand Up @@ -1679,7 +1679,7 @@ def time(self):
Returns numpy array of datetime.time. The time part of the Timestamps.
"""
return self._maybe_mask_results(libalgos.arrmap_object(
self.asobject.values,
self.astype(object).values,
lambda x: np.nan if x is libts.NaT else x.time()))

@property
Expand Down Expand Up @@ -1789,7 +1789,7 @@ def insert(self, loc, item):

# fall back to object index
if isinstance(item, compat.string_types):
return self.asobject.insert(loc, item)
return self.astype(object).insert(loc, item)
raise TypeError(
"cannot insert DatetimeIndex with incompatible label")

Expand Down
14 changes: 7 additions & 7 deletions pandas/core/indexes/period.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def _int64index(self):

@property
def values(self):
return self.asobject.values
return self.astype(object).values

@property
def _values(self):
Expand All @@ -428,7 +428,7 @@ def __array__(self, dtype=None):
if is_integer_dtype(dtype):
return self.asi8
else:
return self.asobject.values
return self.astype(object).values

def __array_wrap__(self, result, context=None):
"""
Expand Down Expand Up @@ -476,7 +476,7 @@ def _to_embed(self, keep_tz=False, dtype=None):
if dtype is not None:
return self.astype(dtype)._to_embed(keep_tz=keep_tz)

return self.asobject.values
return self.astype(object).values

@property
def _formatter_func(self):
Expand Down Expand Up @@ -506,7 +506,7 @@ def asof_locs(self, where, mask):
def astype(self, dtype, copy=True, how='start'):
dtype = pandas_dtype(dtype)
if is_object_dtype(dtype):
return self.asobject
return self._box_values_as_index()
elif is_integer_dtype(dtype):
if copy:
return self._int64index.copy()
Expand Down Expand Up @@ -656,7 +656,7 @@ def end_time(self):

def _mpl_repr(self):
# how to represent ourselves to matplotlib
return self.asobject.values
return self.astype(object).values

def to_timestamp(self, freq=None, how='start'):
"""
Expand Down Expand Up @@ -971,7 +971,7 @@ def _convert_tolerance(self, tolerance, target):

def insert(self, loc, item):
if not isinstance(item, Period) or self.freq != item.freq:
return self.asobject.insert(loc, item)
return self.astype(object).insert(loc, item)

idx = np.concatenate((self[:loc].asi8, np.array([item.ordinal]),
self[loc:].asi8))
Expand Down Expand Up @@ -1018,7 +1018,7 @@ def _apply_meta(self, rawarr):
def _format_native_types(self, na_rep=u('NaT'), date_format=None,
**kwargs):

values = self.asobject.values
values = self.astype(object).values

if date_format:
formatter = lambda dt: dt.strftime(date_format)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ def astype(self, dtype, copy=True):
dtype = np.dtype(dtype)

if is_object_dtype(dtype):
return self.asobject
return self._box_values_as_index()
elif is_timedelta64_ns_dtype(dtype):
if copy is True:
return self.copy()
Expand Down Expand Up @@ -883,7 +883,7 @@ def insert(self, loc, item):

# fall back to object index
if isinstance(item, compat.string_types):
return self.asobject.insert(loc, item)
return self.astype(object).insert(loc, item)
raise TypeError(
"cannot insert TimedeltaIndex with incompatible label")

Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,8 @@ def _setitem_with_indexer(self, indexer, value):
new_values = np.concatenate([self.obj._values,
new_values])
except TypeError:
new_values = np.concatenate([self.obj.asobject,
as_obj = self.obj.astype(object)
new_values = np.concatenate([as_obj,
new_values])
self.obj._data = self.obj._constructor(
new_values, index=new_index, name=self.obj.name)._data
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -2191,7 +2191,7 @@ def _try_coerce_args(self, values, other):

if isinstance(other, ABCDatetimeIndex):
# to store DatetimeTZBlock as object
other = other.asobject.values
other = other.astype(object).values

return values, False, other, False

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,7 @@ def wrapper(self, other, axis=None):
# tested in test_nat_comparisons
# (pandas.tests.series.test_operators.TestSeriesOperators)
return self._constructor(na_op(self.values,
other.asobject.values),
other.astype(object).values),
index=self.index)

return self._constructor(na_op(self.values, np.asarray(other)),
Expand Down
16 changes: 10 additions & 6 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ class Series(base.IndexOpsMixin, generic.NDFrame):
_metadata = ['name']
_accessors = frozenset(['dt', 'cat', 'str'])
_deprecations = generic.NDFrame._deprecations | frozenset(
['sortlevel', 'reshape', 'get_value', 'set_value', 'from_csv'])
['asobject', 'sortlevel', 'reshape', 'get_value', 'set_value',
'from_csv'])
_allow_index_ops = True

def __init__(self, data=None, index=None, dtype=None, name=None,
Expand Down Expand Up @@ -449,12 +450,15 @@ def get_values(self):

@property
def asobject(self):
"""
"""DEPRECATED: Use ``astype(object)`` instead.
return object Series which contains boxed values
*this is an internal non-public method*
"""
return self._data.asobject
warnings.warn("'asobject' is deprecated. Use 'astype(object)'"
" instead", FutureWarning, stacklevel=2)
return self.astype(object).values

# ops
def ravel(self, order='C'):
Expand Down Expand Up @@ -1322,7 +1326,7 @@ def unique(self):
# to return an object array of tz-aware Timestamps

# TODO: it must return DatetimeArray with tz in pandas 2.0
result = result.asobject.values
result = result.astype(object).values

return result

Expand Down Expand Up @@ -2549,7 +2553,7 @@ def apply(self, func, convert_dtype=True, args=(), **kwds):
if is_extension_type(self.dtype):
mapped = self._values.map(f)
else:
values = self.asobject
values = self.astype(object).values
mapped = lib.map_infer(values, f, convert=convert_dtype)

if len(mapped) and isinstance(mapped[0], Series):
Expand Down Expand Up @@ -3125,7 +3129,7 @@ def _sanitize_index(data, index, copy=False):
if isinstance(data, ABCIndexClass) and not copy:
pass
elif isinstance(data, PeriodIndex):
data = data.asobject
data = data.astype(object).values
elif isinstance(data, DatetimeIndex):
data = data._to_embed(keep_tz=True)
elif isinstance(data, np.ndarray):
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2231,7 +2231,7 @@ class Datetime64TZFormatter(Datetime64Formatter):
def _format_strings(self):
""" we by definition have a TZ """

values = self.values.asobject
values = self.values.astype(object)
is_dates_only = _is_dates_only(values)
formatter = (self.formatter or
_get_format_datetime64(is_dates_only,
Expand Down
3 changes: 2 additions & 1 deletion pandas/plotting/_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,8 @@ def __call__(self):
tz = self.tz.tzname(None)
st = _from_ordinal(dates.date2num(dmin)) # strip tz
ed = _from_ordinal(dates.date2num(dmax))
all_dates = date_range(start=st, end=ed, freq=freq, tz=tz).asobject
all_dates = date_range(start=st, end=ed,
freq=freq, tz=tz).astype(object)

try:
if len(all_dates) > 0:
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,8 +501,8 @@ def test_constructor_period(self):
assert df['b'].dtype == 'object'

# list of periods
df = pd.DataFrame({'a': a.asobject.tolist(),
'b': b.asobject.tolist()})
df = pd.DataFrame({'a': a.astype(object).tolist(),
'b': b.astype(object).tolist()})
assert df['a'].dtype == 'object'
assert df['b'].dtype == 'object'

Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,10 @@ def test_map_dictlike(self, mapper):
expected = pd.Index([np.nan] * len(self.index))
result = self.index.map(mapper([], []))
tm.assert_index_equal(result, expected)

def test_asobject_deprecated(self):
# GH18572
d = self.create_index()
with tm.assert_produces_warning(FutureWarning):
i = d.asobject
assert isinstance(i, pd.Index)
Loading

0 comments on commit aa5b6e6

Please sign in to comment.