Skip to content

Optimising Series.nunique for Nan values #40865 #41236

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

Merged
merged 8 commits into from
May 3, 2021
Merged
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
8 changes: 8 additions & 0 deletions asv_bench/benchmarks/frame_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,14 @@ def time_frame_nunique(self):
self.df.nunique()


class SeriesNuniqueWithNan:
def setup(self):
self.ser = Series(100000 * (100 * [np.nan] + list(range(100)))).astype(float)

def time_series_nunique_nan(self):
self.ser.nunique()


class Duplicated:
def setup(self):
n = 1 << 20
Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ Performance improvements
- Performance improvement in the conversion of pyarrow boolean array to a pandas nullable boolean array (:issue:`41051`)
- Performance improvement for concatenation of data with type :class:`CategoricalDtype` (:issue:`40193`)
- Performance improvement in :meth:`.GroupBy.cummin` and :meth:`.GroupBy.cummax` with nullable data types (:issue:`37493`)
-
- Performance improvement in :meth:`Series.nunique` with nan values (:issue:`40865`)

.. ---------------------------------------------------------------------------

Expand Down
6 changes: 4 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1040,8 +1040,10 @@ def nunique(self, dropna: bool = True) -> int:
>>> s.nunique()
4
"""
obj = remove_na_arraylike(self) if dropna else self
return len(obj.unique())
uniqs = self.unique()
if dropna:
uniqs = remove_na_arraylike(uniqs)
return len(uniqs)

@property
def is_unique(self) -> bool:
Expand Down