diff --git a/doc/source/reference/api/pandas.Series.__invert__.rst b/doc/source/reference/api/pandas.Series.__invert__.rst new file mode 100644 index 0000000000000..0c82307bca351 --- /dev/null +++ b/doc/source/reference/api/pandas.Series.__invert__.rst @@ -0,0 +1,53 @@ +.. currentmodule:: pandas + +pandas.Series.__invert__ +======================== + +Elementwise invert (``~``) for :class:`pandas.Series`. + +**Signature** + +``Series.__invert__(self) -> Series`` + +**Summary** + +For boolean and nullable-boolean dtypes, ``~s`` toggles the mask +(``True`` ↔ ``False``) and propagates ``pd.NA``. For integer dtypes, +``~`` performs bitwise invert as in Python. + +.. seealso:: + :ref:`Boolean indexing ` + +**Examples** + +Boolean / nullable boolean:: + + >>> s = pd.Series([True, pd.NA, False], dtype="boolean") + >>> ~s + 0 False + 1 + 2 True + dtype: boolean + +Integer vs boolean:: + + >>> s_int = pd.Series([0, 1, 2], dtype="int64") + >>> ~s_int + 0 -1 + 1 -2 + 2 -3 + dtype: int64 + +Arrow-backed boolean (if pyarrow installed):: + + >>> s_arrow = pd.Series([True, pd.NA, False], dtype="boolean[pyarrow]") + >>> ~s_arrow + 0 False + 1 + 2 True + dtype: boolean[pyarrow] + +**Notes** + +- In Python’s stdlib, :func:`operator.__invert__` is bitwise invert on integers. + In pandas, ``~`` on boolean arrays is elementwise invert. diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 6006acc8f5e16..a099c48613e21 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -107,6 +107,14 @@ Binary operator functions Series.product Series.dot +Unary operator functions +------------------------ +.. toctree:: + :maxdepth: 1 + + api/pandas.Series.__invert__ + + Function application, GroupBy & window -------------------------------------- .. autosummary:: diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst index ebd1791c0f4ad..413ddb7a23155 100644 --- a/doc/source/user_guide/indexing.rst +++ b/doc/source/user_guide/indexing.rst @@ -811,6 +811,10 @@ evaluate an expression such as ``df['A'] > 2 & df['B'] < 3`` as ``df['A'] > (2 & df['B']) < 3``, while the desired evaluation order is ``(df['A'] > 2) & (df['B'] < 3)``. +For toggling boolean masks with the ``~`` operator, see +:meth:`pandas.Series.__invert__`. + + Using a boolean vector to index a Series works exactly as in a NumPy ndarray: .. ipython:: python