Skip to content

PERF: Improve performance of Series.isin() on sets #25812

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

Closed
wants to merge 6 commits into from

Conversation

kykosic
Copy link
Contributor

@kykosic kykosic commented Mar 21, 2019

Issue #25507 pointed out that using DataFrame.isin or Series.isin on a set took extremely long due to the set being first converted to a list then back to a hash table to lookup values. This fix eliminates that conversion and simply uses the set to directly test membership.

Sample code from issue:

import pandas as pd

squares = set(a**2 for a in range(10000000))
series = pd.Series(range(100))

def test_isin():
    _ = series.isin(squares)

%timeit test_isin()

Output:

Before:
3.89 s ± 66.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

After:
134 µs ± 11.3 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

There are already several unit tests covering this function on sets with different dtypes. Additionally, I added an additional asv benchmark for sets:

series_methods.IsIn.time_isin
======== =============
dtype
-------- -------------
int64    1.46±0.04ms
uint64    1.76±0.1ms
object    3.53±0.2ms
======== =============

series_methods.IsIn.time_isin_set
======== =============
dtype
-------- -------------
int64    1.58±0.03ms
uint64   1.61±0.06ms
object   3.24±0.04ms
======== =============

If the additional benchmark is overkill I can of course remove it.

@@ -395,6 +395,14 @@ def isin(comps, values):
" to isin(), you passed a [{values_type}]"
.format(values_type=type(values).__name__))

# GH 25507
# if `values` is a set, directly use it instead of hashing a list
if isinstance(values, set):
Copy link
Contributor

Choose a reason for hiding this comment

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

i think we have an is_set_like (otherwise pls create one)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I didn't find an existing one so I have added it.

@codecov
Copy link

codecov bot commented Mar 21, 2019

Codecov Report

Merging #25812 into master will increase coverage by <.01%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master   #25812      +/-   ##
==========================================
+ Coverage   91.27%   91.27%   +<.01%     
==========================================
  Files         173      173              
  Lines       53002    53007       +5     
==========================================
+ Hits        48375    48381       +6     
+ Misses       4627     4626       -1
Flag Coverage Δ
#multiple 89.83% <100%> (ø) ⬆️
#single 41.76% <20%> (-0.01%) ⬇️
Impacted Files Coverage Δ
pandas/core/algorithms.py 94.83% <100%> (+0.03%) ⬆️
pandas/util/testing.py 89.4% <0%> (+0.1%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update fbe2523...a083384. Read the comment docs.

@codecov
Copy link

codecov bot commented Mar 21, 2019

Codecov Report

Merging #25812 into master will increase coverage by 0.14%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master   #25812      +/-   ##
==========================================
+ Coverage    91.3%   91.45%   +0.14%     
==========================================
  Files         173      172       -1     
  Lines       53004    52899     -105     
==========================================
- Hits        48397    48380      -17     
+ Misses       4607     4519      -88
Flag Coverage Δ
#multiple 90.02% <100%> (+0.14%) ⬆️
#single 41.82% <42.85%> (+0.05%) ⬆️
Impacted Files Coverage Δ
pandas/core/dtypes/common.py 96.78% <ø> (ø) ⬆️
pandas/core/dtypes/inference.py 98.46% <100%> (+0.04%) ⬆️
pandas/core/algorithms.py 94.83% <100%> (+0.03%) ⬆️
pandas/io/feather_format.py 89.47% <0%> (-0.27%) ⬇️
pandas/core/computation/engines.py 88.7% <0%> (-0.18%) ⬇️
pandas/plotting/_tools.py 78.65% <0%> (-0.12%) ⬇️
pandas/util/testing.py 89.3% <0%> (-0.11%) ⬇️
pandas/io/excel/_xlrd.py 93.93% <0%> (-0.1%) ⬇️
pandas/core/tools/datetimes.py 84.59% <0%> (-0.05%) ⬇️
pandas/core/computation/align.py 97.82% <0%> (-0.03%) ⬇️
... and 14 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 9e27f12...88752e2. Read the comment docs.

@WillAyd WillAyd added the Performance Memory or execution speed performance label Mar 21, 2019
@@ -395,6 +395,14 @@ def isin(comps, values):
" to isin(), you passed a [{values_type}]"
.format(values_type=type(values).__name__))

# GH 25507
Copy link
Contributor

Choose a reason for hiding this comment

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

I would like you to integrate this with the other impl., meaning skip the set-ifying if its a set, but otherwise dispatch the actual isin operation. I suspect this will work only in some of the tests cases (but we aren't fully testing it here).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure what you mean by the other implementation or the actual isin operator. Do you mean let the rest of this function run but without the type cast? Or attempt to call comps.isin? It seems that would fail if comps was an ndarray.

Copy link
Contributor

Choose a reason for hiding this comment

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

what i mean is you can skip the list-ifying if its a set, but don't actually do the comp in values. as I said I suspect this actually doesn't work (some tests are failing) and if we add sets to a fair number of tests they will fail. The reason is that these all must be the same types exactly e.g. comp is often a int while values maybe be an np.int. we already fully handle this path, so you need to fit in.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The tests that failed are unrelated to my changes (conda connection issues on setup). I will add more tests for set values, but dispatching the current path of isin will destroy the performance gain this change intended to fix.

I can't find any situations which cause this change to fail. The int vs np.int works fine, and I can create tests around such cases.

Copy link
Contributor

Choose a reason for hiding this comment

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

you are creating a new path which makes the codes more complex ; we already have too many paths here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Okay then feel free to close this pull request; the current path cannot support this performance change.

Copy link
Contributor

Choose a reason for hiding this comment

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

as I said this needs to integrate with the existing isin tests. this needs to happen before this patch is considered.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So the new patch works well for every test case except NaN types. The current paths ensure that an array containing NaN when compared against a collection with NaN in it returns True. However using Python sets NaN != NaN so it will return False (not sure of the reasoning, but I think current implementation goes against IEEE).

This means that .isin({np.nan}) and .isin([np.nan]) will have different results, and I don't know of a way to resolve this without introducing an O(n) check that destroys the performance fix.

Closing this pull request as I don't think we can implement this performance change without this regression.

if is_set_like(values):
result = np.empty_like(comps, dtype=np.bool)
for i, comp in enumerate(comps):
result[i] = comp in values
Copy link
Contributor

Choose a reason for hiding this comment

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

for each test in test_algorithms for isin, add an arg that also is a set (for as many tests as possible)

@jreback jreback added the Reshaping Concat, Merge/Join, Stack/Unstack, Explode label Mar 21, 2019
@@ -395,6 +395,14 @@ def isin(comps, values):
" to isin(), you passed a [{values_type}]"
.format(values_type=type(values).__name__))

# GH 25507
Copy link
Contributor

Choose a reason for hiding this comment

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

what i mean is you can skip the list-ifying if its a set, but don't actually do the comp in values. as I said I suspect this actually doesn't work (some tests are failing) and if we add sets to a fair number of tests they will fail. The reason is that these all must be the same types exactly e.g. comp is often a int while values maybe be an np.int. we already fully handle this path, so you need to fit in.

@@ -395,6 +395,14 @@ def isin(comps, values):
" to isin(), you passed a [{values_type}]"
.format(values_type=type(values).__name__))

# GH 25507
Copy link
Contributor

Choose a reason for hiding this comment

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

as I said this needs to integrate with the existing isin tests. this needs to happen before this patch is considered.

@kykosic kykosic closed this Mar 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Performance Memory or execution speed performance Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Projects
None yet
Development

Successfully merging this pull request may close these issues.

pandas.Series.isin() is slow on large sets due to conversion of set to list
3 participants