Skip to content

Commit 2c15064

Browse files
authored
Document constant check in series
Closes pandas-dev#54033
1 parent c126eeb commit 2c15064

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

doc/source/user_guide/cookbook.rst

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1488,3 +1488,35 @@ of the data values:
14881488
{"height": [60, 70], "weight": [100, 140, 180], "sex": ["Male", "Female"]}
14891489
)
14901490
df
1491+
1492+
Constant series
1493+
---------------
1494+
1495+
To assess if a series has a constant value, we can check if ``series.nunique() == 1``.
1496+
However, a more performant approach, that does not count all unique values first, is:
1497+
1498+
.. ipython:: python
1499+
1500+
v = s.values
1501+
is_constant = v.shape[0] > 0 and (s[0] == s).all()
1502+
1503+
This approach assumes that the series does not contain missing values.
1504+
For the case that we would drop NA values, we can simply remove those values first:
1505+
1506+
.. ipython:: python
1507+
1508+
from pandas.core.dtypes.missing import remove_na_arraylike
1509+
1510+
v = s.values
1511+
v = remove_na_arraylike(v)
1512+
is_constant = v.shape[0] > 0 and (s[0] == s).all()
1513+
1514+
If missing values are considered distinct from any other value, then one could use:
1515+
1516+
.. ipython:: python
1517+
1518+
v = s.values
1519+
is_constant = v.shape[0] > 0 and ((s[0] == s).all() or not pd.notna(v).any())
1520+
1521+
(Note that this example does not disambiguate between `np.nan`, `pd.NA` and `None`)
1522+

0 commit comments

Comments
 (0)