Skip to content

Commit aa5b6e6

Browse files
topper-123jorisvandenbossche
authored andcommitted
DEPR: deprecate .asobject property (#18572)
1 parent 6e56195 commit aa5b6e6

32 files changed

+158
-127
lines changed

asv_bench/benchmarks/index_object.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def setup(self):
1212
if (self.rng.dtype == object):
1313
self.idx_rng = self.rng.view(Index)
1414
else:
15-
self.idx_rng = self.rng.asobject
15+
self.idx_rng = self.rng.astype(object)
1616
self.idx_rng2 = self.idx_rng[:(-1)]
1717

1818
# other datetime

doc/source/whatsnew/v0.22.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ Deprecations
124124

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

129129
.. _whatsnew_0220.prior_deprecations:
130130

pandas/_libs/algos_common_helper.pxi.in

+2-2
Original file line numberDiff line numberDiff line change
@@ -552,8 +552,8 @@ cpdef ensure_object(object arr):
552552
return arr
553553
else:
554554
return arr.astype(np.object_)
555-
elif hasattr(arr, 'asobject'):
556-
return arr.asobject
555+
elif hasattr(arr, '_box_values_as_index'):
556+
return arr._box_values_as_index()
557557
else:
558558
return np.array(arr, dtype=np.object_)
559559

pandas/core/accessor.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
class DirNamesMixin(object):
1212
_accessors = frozenset([])
13-
_deprecations = frozenset([])
13+
_deprecations = frozenset(['asobject'])
1414

1515
def _dir_deletions(self):
1616
""" delete unwanted __dir__ for this object """

pandas/core/algorithms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ def unique(values):
369369
# to return an object array of tz-aware Timestamps
370370

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

374374
return uniques
375375

pandas/core/dtypes/concat.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ def convert_to_pydatetime(x, axis):
401401
# if dtype is of datetimetz or timezone
402402
if x.dtype.kind == _NS_DTYPE.kind:
403403
if getattr(x, 'tz', None) is not None:
404-
x = x.asobject.values
404+
x = x.astype(object).values
405405
else:
406406
shape = x.shape
407407
x = tslib.ints_to_pydatetime(x.view(np.int64).ravel(),
@@ -479,7 +479,7 @@ def _concat_index_asobject(to_concat, name=None):
479479
"""
480480

481481
klasses = ABCDatetimeIndex, ABCTimedeltaIndex, ABCPeriodIndex
482-
to_concat = [x.asobject if isinstance(x, klasses) else x
482+
to_concat = [x.astype(object) if isinstance(x, klasses) else x
483483
for x in to_concat]
484484

485485
from pandas import Index

pandas/core/frame.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3330,7 +3330,7 @@ class max type
33303330

33313331
def _maybe_casted_values(index, labels=None):
33323332
if isinstance(index, PeriodIndex):
3333-
values = index.asobject.values
3333+
values = index.astype(object).values
33343334
elif isinstance(index, DatetimeIndex) and index.tz is not None:
33353335
values = index
33363336
else:
@@ -5077,7 +5077,7 @@ def applymap(self, func):
50775077
def infer(x):
50785078
if x.empty:
50795079
return lib.map_infer(x, func)
5080-
return lib.map_infer(x.asobject, func)
5080+
return lib.map_infer(x.astype(object).values, func)
50815081

50825082
return self.apply(infer)
50835083

pandas/core/indexes/datetimelike.py

+15-6
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,13 @@ def _box_values(self, values):
242242
"""
243243
return lib.map_infer(values, self._box_func)
244244

245+
def _box_values_as_index(self):
246+
"""
247+
return object Index which contains boxed values
248+
"""
249+
from pandas.core.index import Index
250+
return Index(self._box_values(self.asi8), name=self.name, dtype=object)
251+
245252
def _format_with_header(self, header, **kwargs):
246253
return header + list(self._format_native_types(**kwargs))
247254

@@ -360,7 +367,7 @@ def map(self, f):
360367
raise TypeError('The map function must return an Index object')
361368
return result
362369
except Exception:
363-
return self.asobject.map(f)
370+
return self.astype(object).map(f)
364371

365372
def sort_values(self, return_indexer=False, ascending=True):
366373
"""
@@ -424,13 +431,15 @@ def _isnan(self):
424431

425432
@property
426433
def asobject(self):
427-
"""
434+
"""DEPRECATED: Use ``astype(object)`` instead.
435+
428436
return object Index which contains boxed values
429437
430438
*this is an internal non-public method*
431439
"""
432-
from pandas.core.index import Index
433-
return Index(self._box_values(self.asi8), name=self.name, dtype=object)
440+
warnings.warn("'asobject' is deprecated. Use 'astype(object)'"
441+
" instead", FutureWarning, stacklevel=2)
442+
return self.astype(object)
434443

435444
def _convert_tolerance(self, tolerance, target):
436445
tolerance = np.asarray(to_timedelta(tolerance, box=False))
@@ -468,7 +477,7 @@ def tolist(self):
468477
"""
469478
return a list of the underlying data
470479
"""
471-
return list(self.asobject)
480+
return list(self.astype(object))
472481

473482
def min(self, axis=None, *args, **kwargs):
474483
"""
@@ -746,7 +755,7 @@ def isin(self, values):
746755
try:
747756
values = type(self)(values)
748757
except ValueError:
749-
return self.asobject.isin(values)
758+
return self.astype(object).isin(values)
750759

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

pandas/core/indexes/datetimes.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -907,7 +907,7 @@ def to_datetime(self, dayfirst=False):
907907
def astype(self, dtype, copy=True):
908908
dtype = pandas_dtype(dtype)
909909
if is_object_dtype(dtype):
910-
return self.asobject
910+
return self._box_values_as_index()
911911
elif is_integer_dtype(dtype):
912912
return Index(self.values.astype('i8', copy=copy), name=self.name,
913913
dtype='i8')
@@ -1679,7 +1679,7 @@ def time(self):
16791679
Returns numpy array of datetime.time. The time part of the Timestamps.
16801680
"""
16811681
return self._maybe_mask_results(libalgos.arrmap_object(
1682-
self.asobject.values,
1682+
self.astype(object).values,
16831683
lambda x: np.nan if x is libts.NaT else x.time()))
16841684

16851685
@property
@@ -1789,7 +1789,7 @@ def insert(self, loc, item):
17891789

17901790
# fall back to object index
17911791
if isinstance(item, compat.string_types):
1792-
return self.asobject.insert(loc, item)
1792+
return self.astype(object).insert(loc, item)
17931793
raise TypeError(
17941794
"cannot insert DatetimeIndex with incompatible label")
17951795

pandas/core/indexes/period.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,7 @@ def _int64index(self):
418418

419419
@property
420420
def values(self):
421-
return self.asobject.values
421+
return self.astype(object).values
422422

423423
@property
424424
def _values(self):
@@ -428,7 +428,7 @@ def __array__(self, dtype=None):
428428
if is_integer_dtype(dtype):
429429
return self.asi8
430430
else:
431-
return self.asobject.values
431+
return self.astype(object).values
432432

433433
def __array_wrap__(self, result, context=None):
434434
"""
@@ -476,7 +476,7 @@ def _to_embed(self, keep_tz=False, dtype=None):
476476
if dtype is not None:
477477
return self.astype(dtype)._to_embed(keep_tz=keep_tz)
478478

479-
return self.asobject.values
479+
return self.astype(object).values
480480

481481
@property
482482
def _formatter_func(self):
@@ -506,7 +506,7 @@ def asof_locs(self, where, mask):
506506
def astype(self, dtype, copy=True, how='start'):
507507
dtype = pandas_dtype(dtype)
508508
if is_object_dtype(dtype):
509-
return self.asobject
509+
return self._box_values_as_index()
510510
elif is_integer_dtype(dtype):
511511
if copy:
512512
return self._int64index.copy()
@@ -656,7 +656,7 @@ def end_time(self):
656656

657657
def _mpl_repr(self):
658658
# how to represent ourselves to matplotlib
659-
return self.asobject.values
659+
return self.astype(object).values
660660

661661
def to_timestamp(self, freq=None, how='start'):
662662
"""
@@ -971,7 +971,7 @@ def _convert_tolerance(self, tolerance, target):
971971

972972
def insert(self, loc, item):
973973
if not isinstance(item, Period) or self.freq != item.freq:
974-
return self.asobject.insert(loc, item)
974+
return self.astype(object).insert(loc, item)
975975

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

1021-
values = self.asobject.values
1021+
values = self.astype(object).values
10221022

10231023
if date_format:
10241024
formatter = lambda dt: dt.strftime(date_format)

pandas/core/indexes/timedeltas.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ def astype(self, dtype, copy=True):
482482
dtype = np.dtype(dtype)
483483

484484
if is_object_dtype(dtype):
485-
return self.asobject
485+
return self._box_values_as_index()
486486
elif is_timedelta64_ns_dtype(dtype):
487487
if copy is True:
488488
return self.copy()
@@ -883,7 +883,7 @@ def insert(self, loc, item):
883883

884884
# fall back to object index
885885
if isinstance(item, compat.string_types):
886-
return self.asobject.insert(loc, item)
886+
return self.astype(object).insert(loc, item)
887887
raise TypeError(
888888
"cannot insert TimedeltaIndex with incompatible label")
889889

pandas/core/indexing.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,8 @@ def _setitem_with_indexer(self, indexer, value):
405405
new_values = np.concatenate([self.obj._values,
406406
new_values])
407407
except TypeError:
408-
new_values = np.concatenate([self.obj.asobject,
408+
as_obj = self.obj.astype(object)
409+
new_values = np.concatenate([as_obj,
409410
new_values])
410411
self.obj._data = self.obj._constructor(
411412
new_values, index=new_index, name=self.obj.name)._data

pandas/core/internals.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2191,7 +2191,7 @@ def _try_coerce_args(self, values, other):
21912191

21922192
if isinstance(other, ABCDatetimeIndex):
21932193
# to store DatetimeTZBlock as object
2194-
other = other.asobject.values
2194+
other = other.astype(object).values
21952195

21962196
return values, False, other, False
21972197

pandas/core/ops.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -850,7 +850,7 @@ def wrapper(self, other, axis=None):
850850
# tested in test_nat_comparisons
851851
# (pandas.tests.series.test_operators.TestSeriesOperators)
852852
return self._constructor(na_op(self.values,
853-
other.asobject.values),
853+
other.astype(object).values),
854854
index=self.index)
855855

856856
return self._constructor(na_op(self.values, np.asarray(other)),

pandas/core/series.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,8 @@ class Series(base.IndexOpsMixin, generic.NDFrame):
149149
_metadata = ['name']
150150
_accessors = frozenset(['dt', 'cat', 'str'])
151151
_deprecations = generic.NDFrame._deprecations | frozenset(
152-
['sortlevel', 'reshape', 'get_value', 'set_value', 'from_csv'])
152+
['asobject', 'sortlevel', 'reshape', 'get_value', 'set_value',
153+
'from_csv'])
153154
_allow_index_ops = True
154155

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

450451
@property
451452
def asobject(self):
452-
"""
453+
"""DEPRECATED: Use ``astype(object)`` instead.
454+
453455
return object Series which contains boxed values
454456
455457
*this is an internal non-public method*
456458
"""
457-
return self._data.asobject
459+
warnings.warn("'asobject' is deprecated. Use 'astype(object)'"
460+
" instead", FutureWarning, stacklevel=2)
461+
return self.astype(object).values
458462

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

13241328
# TODO: it must return DatetimeArray with tz in pandas 2.0
1325-
result = result.asobject.values
1329+
result = result.astype(object).values
13261330

13271331
return result
13281332

@@ -2549,7 +2553,7 @@ def apply(self, func, convert_dtype=True, args=(), **kwds):
25492553
if is_extension_type(self.dtype):
25502554
mapped = self._values.map(f)
25512555
else:
2552-
values = self.asobject
2556+
values = self.astype(object).values
25532557
mapped = lib.map_infer(values, f, convert=convert_dtype)
25542558

25552559
if len(mapped) and isinstance(mapped[0], Series):
@@ -3125,7 +3129,7 @@ def _sanitize_index(data, index, copy=False):
31253129
if isinstance(data, ABCIndexClass) and not copy:
31263130
pass
31273131
elif isinstance(data, PeriodIndex):
3128-
data = data.asobject
3132+
data = data.astype(object).values
31293133
elif isinstance(data, DatetimeIndex):
31303134
data = data._to_embed(keep_tz=True)
31313135
elif isinstance(data, np.ndarray):

pandas/io/formats/format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2231,7 +2231,7 @@ class Datetime64TZFormatter(Datetime64Formatter):
22312231
def _format_strings(self):
22322232
""" we by definition have a TZ """
22332233

2234-
values = self.values.asobject
2234+
values = self.values.astype(object)
22352235
is_dates_only = _is_dates_only(values)
22362236
formatter = (self.formatter or
22372237
_get_format_datetime64(is_dates_only,

pandas/plotting/_converter.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,8 @@ def __call__(self):
363363
tz = self.tz.tzname(None)
364364
st = _from_ordinal(dates.date2num(dmin)) # strip tz
365365
ed = _from_ordinal(dates.date2num(dmax))
366-
all_dates = date_range(start=st, end=ed, freq=freq, tz=tz).asobject
366+
all_dates = date_range(start=st, end=ed,
367+
freq=freq, tz=tz).astype(object)
367368

368369
try:
369370
if len(all_dates) > 0:

pandas/tests/frame/test_constructors.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -501,8 +501,8 @@ def test_constructor_period(self):
501501
assert df['b'].dtype == 'object'
502502

503503
# list of periods
504-
df = pd.DataFrame({'a': a.asobject.tolist(),
505-
'b': b.asobject.tolist()})
504+
df = pd.DataFrame({'a': a.astype(object).tolist(),
505+
'b': b.astype(object).tolist()})
506506
assert df['a'].dtype == 'object'
507507
assert df['b'].dtype == 'object'
508508

pandas/tests/indexes/datetimelike.py

+7
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,10 @@ def test_map_dictlike(self, mapper):
7676
expected = pd.Index([np.nan] * len(self.index))
7777
result = self.index.map(mapper([], []))
7878
tm.assert_index_equal(result, expected)
79+
80+
def test_asobject_deprecated(self):
81+
# GH18572
82+
d = self.create_index()
83+
with tm.assert_produces_warning(FutureWarning):
84+
i = d.asobject
85+
assert isinstance(i, pd.Index)

0 commit comments

Comments
 (0)