From edf58419c57d11e6caabb91a1d833771386447a1 Mon Sep 17 00:00:00 2001 From: shivnaren Date: Mon, 11 Oct 2021 03:05:24 +0530 Subject: [PATCH] ENH: Update isin docs with examples of ~ operator usage (#43959) --- doc/source/user_guide/indexing.rst | 9 +++++++++ pandas/core/frame.py | 7 +++++++ pandas/core/series.py | 11 +++++++++++ 3 files changed, 27 insertions(+) diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst index 584dd0f52ae28..e41f938170417 100644 --- a/doc/source/user_guide/indexing.rst +++ b/doc/source/user_guide/indexing.rst @@ -997,6 +997,15 @@ a list of items you want to check for. df.isin(values) +To return the DataFrame of booleans where the values are *not* in the original DataFrame, +use the ``~`` operator: + +.. ipython:: python + + values = {'ids': ['a', 'b'], 'vals': [1, 3]} + + ~df.isin(values) + Combine DataFrame's ``isin`` with the ``any()`` and ``all()`` methods to quickly select subsets of your data that meet a given criteria. To select a row where each column meets its own criterion: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 76a00071c8adc..6abe82ead45c5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -10559,6 +10559,13 @@ def isin(self, values) -> DataFrame: falcon True True dog False True + To check if ``values`` is *not* in the DataFrame, use the ``~`` operator: + + >>> ~df.isin([0, 2]) + num_legs num_wings + falcon False False + dog True False + When ``values`` is a dict, we can pass values to check for each column separately: diff --git a/pandas/core/series.py b/pandas/core/series.py index 6f48da82169b2..c9263f6ec1d20 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5012,6 +5012,17 @@ def isin(self, values) -> Series: 5 False Name: animal, dtype: bool + To invert the boolean values, use the ``~`` operator: + + >>> ~s.isin(['cow', 'lama']) + 0 False + 1 False + 2 False + 3 True + 4 False + 5 True + Name: animal, dtype: bool + Passing a single string as ``s.isin('lama')`` will raise an error. Use a list of one element instead: