Skip to content

BUG/PERF: algos.union_with_duplicates losing EA dtypes #48900

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 11 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
9 changes: 9 additions & 0 deletions asv_bench/benchmarks/index_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ def time_datetime_difference_disjoint(self):
self.datetime_left.difference(self.datetime_right)


class UnionWithDuplicates:
def setup(self):
self.left = Index(np.repeat(np.arange(1000), 100))
self.right = Index(np.tile(np.arange(500, 1500), 50))

def time_union_with_duplicates(self):
self.left.union(self.right)


class Range:
def setup(self):
self.idx_inc = RangeIndex(start=0, stop=10**6, step=3)
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.6.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ Performance improvements
- Performance improvement in :meth:`MultiIndex.difference` (:issue:`48606`)
- Performance improvement in :meth:`.DataFrameGroupBy.mean`, :meth:`.SeriesGroupBy.mean`, :meth:`.DataFrameGroupBy.var`, and :meth:`.SeriesGroupBy.var` for extension array dtypes (:issue:`37493`)
- Performance improvement in :meth:`MultiIndex.isin` when ``level=None`` (:issue:`48622`)
- Performance improvement in :meth:`Index.union` and :meth:`MultiIndex.union` when index contains duplicates (:issue:`48900`)
- Performance improvement for :meth:`Series.value_counts` with nullable dtype (:issue:`48338`)
- Performance improvement for :class:`Series` constructor passing integer numpy array with nullable dtype (:issue:`48338`)
- Performance improvement for :class:`DatetimeIndex` constructor passing a list (:issue:`48609`)
Expand Down
8 changes: 3 additions & 5 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -1991,13 +1991,11 @@ def union_with_duplicates(lvals: ArrayLike, rvals: ArrayLike) -> ArrayLike:
-----
Caller is responsible for ensuring lvals.dtype == rvals.dtype.
"""
indexer = []
l_count = value_counts(lvals, dropna=False)
r_count = value_counts(rvals, dropna=False)
l_count, r_count = l_count.align(r_count, fill_value=0)
final_count = np.maximum(l_count, r_count).astype("int", copy=False)
Copy link
Member

Choose a reason for hiding this comment

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

You've got 2 MultiIndex checks now. I'd rather handle this on the _union level. Is there any performance benefit of doing it like this?

Additionally, I think you can use unique_vals.take(repeats)
That's more in line with what we are doing elsewhere

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 think we need the MultiIndex checks within union_with_duplicates, otherwise we lose dtypes in there. I'm not sure how how this could be done only on the _union level. Let me know if you have any suggestions.

The repeat logic is not quite a simple take:

np.repeat(unique_vals, repeats)

is equivalent to:

indexer = np.arange(len(unique_vals))
indexer = np.repeat(indexer, repeats)
unique_vals.take(indexer)

Copy link
Member

Choose a reason for hiding this comment

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

You could simply return final_count and handle the rest In the _union level. Alternatively, you could just pass in self and other and handle everything on the lower level. Or add another argument unique_vals to the function

Copy link
Member Author

Choose a reason for hiding this comment

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

Thx, makes sense. I pushed the type checking down into union_with_duplicates.

unique_array = unique(concat_compat([lvals, rvals]))
unique_array = ensure_wrapped_if_datetimelike(unique_array)

for i, value in enumerate(unique_array):
indexer += [i] * int(max(l_count.at[value], r_count.at[value]))
return unique_array.take(indexer)
repeats = final_count.reindex(unique_array).values # type: ignore[attr-defined]
Copy link
Member

Choose a reason for hiding this comment

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

Looks good,

can you refactor this to return the indexer and operate on the MultiIndex in _union()? This avoids losing the dtype.

Copy link
Member Author

Choose a reason for hiding this comment

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

Refactored to preserve EA dtypes. The indexer applies to the combined unique values not the original MI's so I don't think we need to return it.

return np.repeat(unique_array, repeats)