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 2 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
31 changes: 31 additions & 0 deletions doc/source/user_guide/cookbook.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1488,3 +1488,34 @@ 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.values
Copy link
Member

Choose a reason for hiding this comment

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

Could you use .to_numpy() instead of .values in these examples?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

is_constant = v.shape[0] > 0 and (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

from pandas.core.dtypes.missing import remove_na_arraylike

v = s.values
v = remove_na_arraylike(v)
is_constant = v.shape[0] > 0 and (s[0] == s).all()

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

.. ipython:: python

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

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