Skip to content

ENH: Add a Series method which checks whether a Series is constant #59152

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

Closed
Closed
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Other enhancements
- :meth:`DataFrame.fillna` and :meth:`Series.fillna` can now accept ``value=None``; for non-object dtype the corresponding NA value will be used (:issue:`57723`)
- :meth:`DataFrame.pivot_table` and :func:`pivot_table` now allow the passing of keyword arguments to ``aggfunc`` through ``**kwargs`` (:issue:`57884`)
- :meth:`Series.cummin` and :meth:`Series.cummax` now supports :class:`CategoricalDtype` (:issue:`52335`)
- :meth:`Series.isconstant` checks if a :class:`Series` has constant values, with an optional parameter to drop NaN values (:issue:`58806`)
- :meth:`Series.plot` now correctly handle the ``ylabel`` parameter for pie charts, allowing for explicit control over the y-axis label (:issue:`58239`)
- Restore support for reading Stata 104-format and enable reading 103-format dta files (:issue:`58554`)
- Support reading Stata 110-format (Stata 7) dta files (:issue:`47176`)
Expand Down
40 changes: 40 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -5393,6 +5393,46 @@ def isnull(self) -> Series:
"""
return super().isnull()

def isconstant(self, dropna=False):
"""
Return if the series has constant values.

Parameters
----------
dropna : bool, default False
If True, NaN values will be ignored. If False, NaN values will be considered
in the determination of whether the series has constant values.

Returns
-------
bool
True if the series has constant values, False otherwise.

Examples
--------
>>> s = pd.Series([2, 2, 2, 2])
>>> s.isconstant()
True

>>> s = pd.Series([2, 2, 3])
>>> s.isconstant()
False

>>> s = pd.Series([2, 2, 2, np.nan])
>>> s.isconstant(dropna=True)
True

>>> s = pd.Series([2, 2, 2, np.nan])
>>> s.isconstant(dropna=False)
False
"""
v = self.to_numpy()
if dropna:
v = remove_na_arraylike(v)
if v.shape[0] == 0 or not notna(v).any():
return True
return (v[0] == v).all()

# error: Cannot determine type of 'notna'
@doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) # type: ignore[has-type]
def notna(self) -> Series:
Expand Down
65 changes: 65 additions & 0 deletions pandas/tests/series/methods/test_isconstant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import numpy as np

from pandas import Series


class TestSeriesIsConstant:
def test_isconstant(self):
s = Series([2, 2, 2, 2])
result = s.isconstant()
assert result

s = Series([2, 2, 2, 3])
result = s.isconstant()
assert not result

s = Series([])
result = s.isconstant()
assert result

s = Series([5])
result = s.isconstant()
assert result

def test_isconstant_with_nan(self):
s = Series([np.nan])
result = s.isconstant()
assert result

s = Series([np.nan, np.nan])
result = s.isconstant()
assert result

s = Series([np.nan, 1])
result = s.isconstant()
assert not result

s = Series([np.nan, np.nan, 1])
result = s.isconstant()
assert not result

def test_isconstant_with_nan_dropna(self):
s = Series([np.nan])
result = s.isconstant(True)
assert result

s = Series([np.nan, np.nan])
result = s.isconstant(True)
assert result

s = Series([np.nan, 1])
result = s.isconstant(True)
assert result

s = Series([np.nan, np.nan, 1])
result = s.isconstant(True)
assert result

def test_isconstant_mixed_types(self):
s = Series([2, "2", 2])
result = s.isconstant()
assert not result

s = Series([2, 2.0, 2])
result = s.isconstant()
assert result