Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DEPR: deprecate publicfacing .asobject #18477

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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._asobject
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 @@ -84,7 +84,7 @@ Deprecations
~~~~~~~~~~~~

- ``Series.from_array`` and ``SparseSeries.from_array`` are deprecated. Use the normal constructor ``Series(..)`` and ``SparseSeries(..)`` instead (:issue:`18213`).
-
- ``Series.asobject``, ``DatetimeIndex.asobject`` and ``PeriodIndex.asobject``have been deprecated. Use '.astype(object).values' instead (:issue:`18477`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its just .astype(object)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It you follow the call chain down it translates to ser._data.blocks[0].values.astype(object). So I'd say it should be "use .values.astype(object)", which is an ndarray, while .astype(object) returns a Series.

I'll use the form.values.astype(object), unless you comment

-

.. _whatsnew_0220.prior_deprecations:
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._asobject.values
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change usage to .astype(object)


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._asobject.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._asobject 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 @@ -3305,7 +3305,7 @@ class max type

def _maybe_casted_values(index, labels=None):
if isinstance(index, PeriodIndex):
values = index.asobject.values
values = index._asobject.values
elif isinstance(index, DatetimeIndex) and index.tz is not None:
values = index
else:
Expand Down Expand Up @@ -5052,7 +5052,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._asobject, func)

return self.apply(infer)

Expand Down
22 changes: 15 additions & 7 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,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._asobject.map(f)

def sort_values(self, return_indexer=False, ascending=True):
"""
Expand Down Expand Up @@ -421,15 +421,23 @@ def _isnan(self):
return (self.asi8 == iNaT)

@property
def asobject(self):
def _asobject(self):
"""
return object Index which contains boxed values

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove this entirely

*this is an internal non-public method*
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)

@property
def asobject(self):
"""DEPRECATED: Use 'astype(object).values' instead.

Return object Index which contains boxed values
"""
warnings.warn("'.asobject' is deprecated. Use 'astype(object).values'"
" instead", FutureWarning, stacklevel=2)
return self._asobject
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return self.astype(object)


def _convert_tolerance(self, tolerance, target):
tolerance = np.asarray(to_timedelta(tolerance, box=False))
if target.size != tolerance.size and tolerance.size > 1:
Expand Down Expand Up @@ -466,7 +474,7 @@ def tolist(self):
"""
return a list of the underlying data
"""
return list(self.asobject)
return list(self._asobject)

def min(self, axis=None, *args, **kwargs):
"""
Expand Down Expand Up @@ -744,7 +752,7 @@ def isin(self, values):
try:
values = type(self)(values)
except ValueError:
return self.asobject.isin(values)
return self._asobject.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 @@ -906,7 +906,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._asobject
elif is_integer_dtype(dtype):
return Index(self.values.astype('i8', copy=copy), name=self.name,
dtype='i8')
Expand Down Expand Up @@ -1678,7 +1678,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._asobject.values,
lambda x: np.nan if x is libts.NaT else x.time()))

@property
Expand Down Expand Up @@ -1785,7 +1785,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._asobject.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._asobject.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._asobject.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._asobject.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._asobject
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._asobject.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._asobject.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._asobject.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._asobject
elif is_timedelta64_ns_dtype(dtype):
if copy is True:
return self.copy()
Expand Down Expand Up @@ -881,7 +881,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._asobject.insert(loc, item)
raise TypeError(
"cannot insert TimedeltaIndex with incompatible label")

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ 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,
new_values = np.concatenate([self.obj._asobject,
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 @@ -2190,7 +2190,7 @@ def _try_coerce_args(self, values, other):

if isinstance(other, ABCDatetimeIndex):
# to store DatetimeTZBlock as object
other = other.asobject.values
other = other._asobject.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._asobject.values),
index=self.index)

return self._constructor(na_op(self.values, np.asarray(other)),
Expand Down
27 changes: 18 additions & 9 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def __init__(self, data=None, index=None, dtype=None, name=None,
# coerce back to datetime objects for lookup
data = _dict_compat(data)
data = lib.fast_multiget(data,
index.asobject.values,
index._asobject.values,
default=np.nan)
else:
data = np.nan
Expand Down Expand Up @@ -433,14 +433,23 @@ def get_values(self):
return self._data.get_values()

@property
def asobject(self):
def _asobject(self):
"""
return object Series which contains boxed values

*this is an internal non-public method*
Return object Series which contains boxed values
"""
return self._data.asobject

@property
def asobject(self):
"""DEPRECATED: '.asobject' is deprecated. Use 'astype(object).values'
instead.

Return object Series which contains boxed values
"""
warnings.warn("asobject is deprecated. Use 'astype(object).values'"
" instead", FutureWarning, stacklevel=2)
return self._asobject

# ops
def ravel(self, order='C'):
"""
Expand Down Expand Up @@ -1307,7 +1316,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._asobject.values

return result

Expand Down Expand Up @@ -2345,7 +2354,7 @@ def map(self, arg, na_action=None):
raise NotImplementedError
map_f = lambda values, f: values.map(f)
else:
values = self.asobject
values = self._asobject

if na_action == 'ignore':
def map_f(values, f):
Expand Down Expand Up @@ -2567,7 +2576,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._asobject
mapped = lib.map_infer(values, f, convert=convert_dtype)

if len(mapped) and isinstance(mapped[0], Series):
Expand Down Expand Up @@ -3143,7 +3152,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._asobject
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._asobject
is_dates_only = _is_dates_only(values)
formatter = (self.formatter or
_get_format_datetime64(is_dates_only,
Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ 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)._asobject

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 @@ -500,8 +500,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._asobject.tolist(),
'b': b._asobject.tolist()})
assert df['a'].dtype == 'object'
assert df['b'].dtype == 'object'

Expand Down
Loading