Skip to content

DOC: constant check in series #54064

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 9 commits into from
Jul 12, 2023
Merged
Changes from all 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
28 changes: 28 additions & 0 deletions doc/source/user_guide/cookbook.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1488,3 +1488,31 @@ of the data values:
{"height": [60, 70], "weight": [100, 140, 180], "sex": ["Male", "Female"]}
)
df

Constant series
---------------

To assess if a series has a constant value, we can check if ``series.nunique() <= 1``.
However, a more performant approach, that does not count all unique values first, is:

.. ipython:: python

v = s.to_numpy()
is_constant = v.shape[0] == 0 or (s[0] == s).all()

This approach assumes that the series does not contain missing values.
For the case that we would drop NA values, we can simply remove those values first:

.. ipython:: python

v = s.dropna().to_numpy()
is_constant = v.shape[0] == 0 or (s[0] == s).all()

If missing values are considered distinct from any other value, then one could use:

.. ipython:: python

v = s.to_numpy()
is_constant = v.shape[0] == 0 or (s[0] == s).all() or not pd.notna(v).any()

(Note that this example does not disambiguate between ``np.nan``, ``pd.NA`` and ``None``)