| 763 | |
| 764 | @derived_from(pd.DataFrame) |
| 765 | def isin(self, values): |
| 766 | if isinstance(self, DataFrame): |
| 767 | # DataFrame.isin does weird alignment stuff |
| 768 | bad_types = (FrameBase, pd.Series, pd.DataFrame) |
| 769 | else: |
| 770 | bad_types = (FrameBase,) |
| 771 | if isinstance(values, bad_types): |
| 772 | if ( |
| 773 | isinstance(values, FrameBase) |
| 774 | and values.ndim == 1 |
| 775 | and values.npartitions == 1 |
| 776 | ): |
| 777 | # Can broadcast |
| 778 | return new_collection(expr.Isin(self, values=values)) |
| 779 | raise NotImplementedError(f"Passing a {typename(type(values))!r} to `isin`") |
| 780 | |
| 781 | # We wrap values in a delayed for two reasons: |
| 782 | # - avoid serializing data in every task |
| 783 | # - avoid cost of traversal of large list in optimizations |
| 784 | if isinstance(values, list): |
| 785 | # Motivated by https://github.com/dask/dask/issues/9411. This appears to be |
| 786 | # caused by https://github.com/dask/distributed/issues/6368, and further |
| 787 | # exacerbated by the fact that the list contains duplicates. This is a patch until |
| 788 | # we can create a better fix for Serialization. |
| 789 | try: |
| 790 | values = list(set(values)) |
| 791 | except TypeError: |
| 792 | pass |
| 793 | if not any(is_dask_collection(v) for v in values): |
| 794 | # Avoid always passing a numpy array of object dtype |
| 795 | inferred_type = pd.api.types.infer_dtype(values, skipna=False) |
| 796 | object_like = { |
| 797 | "mixed-integer", |
| 798 | "decimal", |
| 799 | "categorical", |
| 800 | "time", |
| 801 | "period", |
| 802 | "mixed", |
| 803 | "unknown-array", |
| 804 | } |
| 805 | if inferred_type in object_like: |
| 806 | values = np.fromiter(values, dtype=object, count=len(values)) |
| 807 | else: |
| 808 | values = np.asarray(values) |
| 809 | |
| 810 | return new_collection( |
| 811 | expr.Isin( |
| 812 | self, |
| 813 | values=expr._DelayedExpr( |
| 814 | delayed(values, name=f"delayed-{_tokenize_deterministic(values)}") |
| 815 | ), |
| 816 | ) |
| 817 | ) |
| 818 | |
| 819 | def _partitions(self, index): |
| 820 | # Used by `partitions` for partition-wise slicing |