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: na_sentinel in factorize #47157

Merged
merged 26 commits into from
Jun 24, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
552775f
DEPR: na_sentinel in factorize
rhshadrach May 27, 2022
79231e7
WIP
rhshadrach May 27, 2022
c822282
DEPR: na_sentinel in factorize
rhshadrach May 27, 2022
05fa0ca
Fixups
rhshadrach May 28, 2022
f626dd8
Fixups
rhshadrach May 28, 2022
a15e43a
black
rhshadrach May 28, 2022
9a33637
fixup
rhshadrach May 28, 2022
46e7a8d
docs
rhshadrach May 28, 2022
b1edc89
Merge branch 'depr_na_sentinel' of https://github.com/rhshadrach/pand…
rhshadrach May 31, 2022
c8d6fa2
Merge branch 'main' of https://github.com/pandas-dev/pandas into depr…
rhshadrach May 31, 2022
0fd1ea7
newline
rhshadrach May 31, 2022
465ab2b
Warn on class construction, rework pd.factorize warnings
rhshadrach Jun 1, 2022
6b4917c
FutureWarning -> DeprecationWarning
rhshadrach Jun 1, 2022
d8e3d6b
Remove old comment
rhshadrach Jun 1, 2022
0111eef
Merge branch 'main' of https://github.com/pandas-dev/pandas into depr…
rhshadrach Jun 10, 2022
39b3747
backticks in warnings, revert datetimelike, avoid catch_warnings
rhshadrach Jun 10, 2022
5842053
fixup for warnings
rhshadrach Jun 10, 2022
945bb04
mypy fixups
rhshadrach Jun 11, 2022
8f8cb18
Merge branch 'main' of https://github.com/pandas-dev/pandas into depr…
rhshadrach Jun 11, 2022
9630edc
Merge branch 'main' into depr_na_sentinel
jreback Jun 11, 2022
5524d53
Move resolve_na_sentinel
rhshadrach Jun 12, 2022
fcd8a75
Merge branch 'main' of https://github.com/pandas-dev/pandas into depr…
rhshadrach Jun 12, 2022
c615de4
Merge branch 'main' of https://github.com/pandas-dev/pandas into depr…
rhshadrach Jun 19, 2022
80aaf5e
Merge branch 'main' of https://github.com/pandas-dev/pandas into depr…
rhshadrach Jun 23, 2022
dc97a7b
Remove underscores
rhshadrach Jun 24, 2022
eb6d5a1
Merge branch 'main' of https://github.com/pandas-dev/pandas into depr…
rhshadrach Jun 24, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,7 @@ Other Deprecations
- Deprecated the ``closed`` argument in :class:`IntervalArray` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
- Deprecated the ``closed`` argument in :class:`intervaltree` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
- Deprecated the ``closed`` argument in :class:`ArrowInterval` in favor of ``inclusive`` argument; In a future version passing ``closed`` will raise (:issue:`40245`)
- Deprecated the argument ``na_sentinel`` in :func:`factorize`, :meth:`Index.factorize`, and :meth:`.ExtensionArray.factorize`; pass ``use_na_sentinel=True`` instead to use the sentinel ``-1`` for NaN values and ``use_na_sentinel=False`` instead of ``na_sentinel=None`` to encode NaN values (:issue:`46910`)

.. ---------------------------------------------------------------------------
.. _whatsnew_150.performance:
Expand Down
51 changes: 43 additions & 8 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
na_value_for_dtype,
)

from pandas.core import common as com
from pandas.core.array_algos.take import take_nd
from pandas.core.construction import (
array as pd_array,
Expand Down Expand Up @@ -580,7 +581,8 @@ def factorize_array(
def factorize(
values,
sort: bool = False,
na_sentinel: int | None = -1,
na_sentinel: int | None | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
size_hint: int | None = None,
) -> tuple[np.ndarray, np.ndarray | Index]:
"""
Expand All @@ -598,7 +600,19 @@ def factorize(
Value to mark "not found". If None, will not drop the NaN
from the uniques of the values.

.. deprecated:: 1.5.0
The na_sentinel argument is deprecated and
will be removed in a future version of pandas. Specify use_na_sentinel as
Comment on lines +610 to +611
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
The na_sentinel argument is deprecated and
will be removed in a future version of pandas. Specify use_na_sentinel as
The `na_sentinel` argument is deprecated and
will be removed in a future version of pandas. Specify `use_na_sentinel` as

Copy link
Member Author

Choose a reason for hiding this comment

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

I took this to mean use backticks for any argument / code in the warnings. I went and implemented that for all warnings.

either True or False.

.. versionchanged:: 1.1.2

use_na_sentinel : bool, default True
If True, the sentinel -1 will be used for NaN values. If False,
NaN values will be encoded as non-negative integers and will not drop the
NaN from the uniques of the values.

.. versionadded:: 1.5.0
{size_hint}\

Returns
Expand Down Expand Up @@ -646,8 +660,8 @@ def factorize(
>>> uniques
array(['a', 'b', 'c'], dtype=object)

Missing values are indicated in `codes` with `na_sentinel`
(``-1`` by default). Note that missing values are never
When ``use_na_sentinel=True`` (the default), missing values are indicated in
the `codes` with the sentinel value ``-1`` and missing values are not
included in `uniques`.

>>> codes, uniques = pd.factorize(['b', None, 'a', 'c', 'b'])
Expand Down Expand Up @@ -682,16 +696,16 @@ def factorize(
Index(['a', 'c'], dtype='object')

If NaN is in the values, and we want to include NaN in the uniques of the
values, it can be achieved by setting ``na_sentinel=None``.
values, it can be achieved by setting ``use_na_sentinel=False``.

>>> values = np.array([1, 2, 1, np.nan])
>>> codes, uniques = pd.factorize(values) # default: na_sentinel=-1
>>> codes, uniques = pd.factorize(values) # default: use_na_sentinel=True
>>> codes
array([ 0, 1, 0, -1])
>>> uniques
array([1., 2.])

>>> codes, uniques = pd.factorize(values, na_sentinel=None)
>>> codes, uniques = pd.factorize(values, use_na_sentinel=False)
>>> codes
array([0, 1, 0, 2])
>>> uniques
Expand All @@ -706,7 +720,13 @@ def factorize(
# responsible only for factorization. All data coercion, sorting and boxing
# should happen here.

# Can't always warn here because EA's factorize will warn too; warn for each
# path below.
passed_na_sentinel = na_sentinel
na_sentinel = com.resolve_na_sentinel(na_sentinel, use_na_sentinel, warn=False)
if isinstance(values, ABCRangeIndex):
# Emit warning if appropriate
_ = com.resolve_na_sentinel(passed_na_sentinel, use_na_sentinel)
return values.factorize(sort=sort)

values = _ensure_arraylike(values)
Expand All @@ -725,15 +745,30 @@ def factorize(
isinstance(values, (ABCDatetimeArray, ABCTimedeltaArray))
and values.freq is not None
):
# Emit warning if appropriate
_ = com.resolve_na_sentinel(passed_na_sentinel, use_na_sentinel)
# The presence of 'freq' means we can fast-path sorting and know there
# aren't NAs
codes, uniques = values.factorize(sort=sort)
return _re_wrap_factorize(original, uniques, codes)

if not isinstance(values.dtype, np.dtype):
elif not isinstance(values.dtype, np.dtype):
# i.e. ExtensionDtype
codes, uniques = values.factorize(na_sentinel=na_sentinel)
if passed_na_sentinel is lib.no_default:
# User didn't specify na_sentinel; avoid warning. Note EA path always
# uses a na_sentinel value.
codes, uniques = values.factorize(use_na_sentinel=True)
elif passed_na_sentinel is None:
# Emit the appropriate warning message for None
_ = com.resolve_na_sentinel(passed_na_sentinel, use_na_sentinel)
codes, uniques = values.factorize(use_na_sentinel=True)
else:
# EA.factorize will warn
codes, uniques = values.factorize(na_sentinel=na_sentinel)
Copy link
Member

Choose a reason for hiding this comment

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

I think we need to distinguish deprecating the keyword that the user passes (I think that is handled above?) vs deprecating what the EA can accept.

Currently, if you have an external EA that has a custom factorize(self, na_sentinel=-1) method, then passing use_na_sentinel will raise an error. So to provide a smooth upgrade path for EA authors (and not users calling Series.factorize()), we might need to check here if the new keyword can be passed or not? (and if not, raising a deprecation warning urging the EA author to update their factorize() implementation)

Copy link
Member

Choose a reason for hiding this comment

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

i guess also worth clarifying is whether we expect the user to call EA.factorize directly vs pd.factorize

Copy link
Member

Choose a reason for hiding this comment

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

Generally we don't "expect" users to directly call EA.factorize, but it is a public method on a public object, so it falls under a deprecation policy (as is being done in this PR already). So I think for EA authors that have a custom EA.factorize, we should recommend doing a similar deprecation in their custom method?

Copy link
Member Author

Choose a reason for hiding this comment

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

Thanks @jorisvandenbossche. I think anyone using a mypy will be getting errors that their signature does not match the base class. I guess this not sufficient? It does seem noisy to add warnings for users, so I added the warning via __init_subclass__ so that it's emitted only once for each EA subclass. The potential downside is that it's emitted regardless of whether the method is used. Note users can silence warnings that are emitted when using pd.factorize even before the EA author adopts the new signature.

This also caught a defect in my previous implementation - pd.factorize was passing use_na_sentinel in some cases, which would cause code to fail if the EA author has not yet made the update. I went the catch_warnings route as I mentioned above.

Copy link
Member Author

@rhshadrach rhshadrach Jun 1, 2022

Choose a reason for hiding this comment

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

Ah, I didn't notice you mentioned deprecation warning instead of future warning. That makes sense and will be less noisy.


else:
# Generate warning for na_sentile if appropriate
_ = com.resolve_na_sentinel(passed_na_sentinel, use_na_sentinel)
values = np.asarray(values) # convert DTA/TDA/MultiIndex
codes, uniques = factorize_array(
values, na_sentinel=na_sentinel, size_hint=size_hint
Expand Down
13 changes: 12 additions & 1 deletion pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import numpy as np

from pandas._libs import lib
from pandas._typing import (
TakeIndexer,
npt,
Expand All @@ -28,6 +29,7 @@
)
from pandas.core.dtypes.missing import isna

from pandas.core import common as com
from pandas.core.arrays.base import ExtensionArray
from pandas.core.indexers import (
check_array_indexer,
Expand Down Expand Up @@ -122,7 +124,16 @@ def dropna(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT:
return type(self)(pc.drop_null(self._data))

@doc(ExtensionArray.factorize)
def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
def factorize(
self,
na_sentinel: int | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
) -> tuple[np.ndarray, ExtensionArray]:
resolved_na_sentinel = com.resolve_na_sentinel(na_sentinel, use_na_sentinel)
if resolved_na_sentinel is None:
raise NotImplementedError("Encoding NaN values is not yet implemented")
else:
na_sentinel = resolved_na_sentinel
encoded = self._data.dictionary_encode()
indices = pa.chunked_array(
[c.indices for c in encoded.chunks], type=encoded.type.index_type
Expand Down
24 changes: 23 additions & 1 deletion pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@

from pandas.core import (
arraylike,
common as com,
missing,
roperator,
)
Expand Down Expand Up @@ -1002,7 +1003,11 @@ def _values_for_factorize(self) -> tuple[np.ndarray, Any]:
"""
return self.astype(object), np.nan

def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
def factorize(
self,
na_sentinel: int | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
) -> tuple[np.ndarray, ExtensionArray]:
"""
Encode the extension array as an enumerated type.

Expand All @@ -1011,6 +1016,18 @@ def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
na_sentinel : int, default -1
Value to use in the `codes` array to indicate missing values.

.. deprecated:: 1.5.0
The na_sentinel argument is deprecated and
will be removed in a future version of pandas. Specify use_na_sentinel
as either True or False.

use_na_sentinel : bool, default True
If True, the sentinel -1 will be used for NaN values. If False,
NaN values will be encoded as non-negative integers and will not drop the
NaN from the uniques of the values.

.. versionadded:: 1.5.0

Returns
-------
codes : ndarray
Expand Down Expand Up @@ -1041,6 +1058,11 @@ def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
# original ExtensionArray.
# 2. ExtensionArray.factorize.
# Complete control over factorization.
resolved_na_sentinel = com.resolve_na_sentinel(na_sentinel, use_na_sentinel)
if resolved_na_sentinel is None:
raise NotImplementedError("Encoding NaN values is not yet implemented")
else:
na_sentinel = resolved_na_sentinel
arr, na_value = self._values_for_factorize()

codes, uniques = factorize_array(
Expand Down
11 changes: 9 additions & 2 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -1899,7 +1899,12 @@ def _with_freq(self, freq):

# --------------------------------------------------------------

def factorize(self, na_sentinel=-1, sort: bool = False):
def factorize(
self,
na_sentinel: int | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
sort: bool = False,
):
if self.freq is not None:
# We must be unique, so can short-circuit (and retain freq)
codes = np.arange(len(self), dtype=np.intp)
Expand All @@ -1909,7 +1914,9 @@ def factorize(self, na_sentinel=-1, sort: bool = False):
uniques = uniques[::-1]
return codes, uniques
# FIXME: shouldn't get here; we are ignoring sort
return super().factorize(na_sentinel=na_sentinel)
return super().factorize(
na_sentinel=na_sentinel, use_na_sentinel=use_na_sentinel
)


# -------------------------------------------------------------------
Expand Down
12 changes: 11 additions & 1 deletion pandas/core/arrays/masked.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
from pandas.core import (
algorithms as algos,
arraylike,
common as com,
missing,
nanops,
ops,
Expand Down Expand Up @@ -869,7 +870,16 @@ def searchsorted(
return self._data.searchsorted(value, side=side, sorter=sorter)

@doc(ExtensionArray.factorize)
def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]:
def factorize(
self,
na_sentinel: int | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
) -> tuple[np.ndarray, ExtensionArray]:
resolved_na_sentinel = com.resolve_na_sentinel(na_sentinel, use_na_sentinel)
if resolved_na_sentinel is None:
raise NotImplementedError("Encoding NaN values is not yet implemented")
else:
na_sentinel = resolved_na_sentinel
arr = self._data
mask = self._mask

Expand Down
10 changes: 8 additions & 2 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -848,13 +848,19 @@ def _values_for_factorize(self):
# Still override this for hash_pandas_object
return np.asarray(self), self.fill_value

def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, SparseArray]:
def factorize(
self,
na_sentinel: int | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
) -> tuple[np.ndarray, SparseArray]:
# Currently, ExtensionArray.factorize -> Tuple[ndarray, EA]
# The sparsity on this is backwards from what Sparse would want. Want
# ExtensionArray.factorize -> Tuple[EA, EA]
# Given that we have to return a dense array of codes, why bother
# implementing an efficient factorize?
codes, uniques = algos.factorize(np.asarray(self), na_sentinel=na_sentinel)
codes, uniques = algos.factorize(
np.asarray(self), na_sentinel=na_sentinel, use_na_sentinel=use_na_sentinel
)
uniques_sp = SparseArray(uniques, dtype=self.dtype)
return codes, uniques_sp

Expand Down
11 changes: 9 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1136,8 +1136,15 @@ def _memory_usage(self, deep: bool = False) -> int:
"""
),
)
def factorize(self, sort: bool = False, na_sentinel: int | None = -1):
return algorithms.factorize(self, sort=sort, na_sentinel=na_sentinel)
def factorize(
self,
sort: bool = False,
na_sentinel: int | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
):
return algorithms.factorize(
self, sort=sort, na_sentinel=na_sentinel, use_na_sentinel=use_na_sentinel
)

_shared_docs[
"searchsorted"
Expand Down
54 changes: 54 additions & 0 deletions pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,3 +704,57 @@ def deprecate_numeric_only_default(cls: type, name: str, deprecate_none: bool =
)

warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())


def resolve_na_sentinel(
Copy link
Contributor

Choose a reason for hiding this comment

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

can you put this somewhere else, closer to where its used

Copy link
Member Author

Choose a reason for hiding this comment

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

Moved to algorithms.

na_sentinel: int | None | lib.NoDefault,
use_na_sentinel: bool | lib.NoDefault,
warn: bool = True,
) -> int | None:
"""
Determine value of na_sentinel for factorize methods.

See GH#46910 for details on the deprecation.

Parameters
----------
na_sentinel : int, None, or lib.no_default
Value passed to the method.
use_na_sentinel : bool or lib.no_default
Value passed to the method.
warn : bool, default True
Whether to emit a warning if a deprecated use is detected.

Returns
-------
Resolved value of na_sentinel.
"""
if na_sentinel is not lib.no_default and use_na_sentinel is not lib.no_default:
raise ValueError(
"Cannot specify both na_sentinel and use_na_sentile; "
f"got na_sentinel={na_sentinel} and use_na_sentinel={use_na_sentinel}"
)
if na_sentinel is lib.no_default:
result = -1 if use_na_sentinel is lib.no_default or use_na_sentinel else None
else:
if warn:
if na_sentinel is None:
msg = (
"Specifying na_sentinel=None is deprecated, specify "
"use_na_sentinel=False instead."
)
elif na_sentinel == -1:
msg = (
"Specifying na_sentinel=-1 is deprecated, specify "
"use_na_sentinel=True instead."
)
else:
msg = (
"Specifying the specific value to use for na_sentinel is "
"deprecated and will be removed in a future version of pandas. "
"Specify na_sentinel=True to use the sentinel value -1, and "
"na_sentinel=False to encode NaN values."
)
warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())
result = na_sentinel
return result
8 changes: 2 additions & 6 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,13 +681,9 @@ def _codes_and_uniques(self) -> tuple[npt.NDArray[np.signedinteger], ArrayLike]:
codes = self.grouping_vector.codes_info
uniques = self.grouping_vector.result_index._values
else:
# GH35667, replace dropna=False with na_sentinel=None
if not self._dropna:
na_sentinel = None
else:
na_sentinel = -1
# GH35667, replace dropna=False with use_na_sentinel=False
codes, uniques = algorithms.factorize(
self.grouping_vector, sort=self._sort, na_sentinel=na_sentinel
self.grouping_vector, sort=self._sort, use_na_sentinel=self._dropna
)
return codes, uniques

Expand Down
7 changes: 6 additions & 1 deletion pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,8 +510,13 @@ def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]:
return result

def factorize(
self, sort: bool = False, na_sentinel: int | None = -1
self,
sort: bool = False,
na_sentinel: int | lib.NoDefault = lib.no_default,
use_na_sentinel: bool | lib.NoDefault = lib.no_default,
) -> tuple[npt.NDArray[np.intp], RangeIndex]:
# resolve to emit warning if appropriate
_ = com.resolve_na_sentinel(na_sentinel, use_na_sentinel)
codes = np.arange(len(self), dtype=np.intp)
uniques = self
if sort and self.step < 0:
Expand Down