Skip to content

Commit be09d66

Browse files
authored
DOC: constant check in series (#54064)
* Document constant check in series Closes #54033 * Update cookbook.rst * Update cookbook.rst * empty series is constant * Update cookbook.rst * Update cookbook.rst
1 parent 12c886a commit be09d66

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

doc/source/user_guide/cookbook.rst

+28
Original file line numberDiff line numberDiff line change
@@ -1488,3 +1488,31 @@ 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.to_numpy()
1501+
is_constant = v.shape[0] == 0 or (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+
v = s.dropna().to_numpy()
1509+
is_constant = v.shape[0] == 0 or (s[0] == s).all()
1510+
1511+
If missing values are considered distinct from any other value, then one could use:
1512+
1513+
.. ipython:: python
1514+
1515+
v = s.to_numpy()
1516+
is_constant = v.shape[0] == 0 or (s[0] == s).all() or not pd.notna(v).any()
1517+
1518+
(Note that this example does not disambiguate between ``np.nan``, ``pd.NA`` and ``None``)

0 commit comments

Comments
 (0)