Skip to content

Commit ea9c247

Browse files
fix std/var with complex array (#61646)
* fix std/var with complex array * added whatsnew entry
1 parent a9658a5 commit ea9c247

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,7 @@ Numeric
716716
- Bug in :meth:`DataFrame.cov` raises a ``TypeError`` instead of returning potentially incorrect results or other errors (:issue:`53115`)
717717
- Bug in :meth:`DataFrame.quantile` where the column type was not preserved when ``numeric_only=True`` with a list-like ``q`` produced an empty result (:issue:`59035`)
718718
- Bug in :meth:`Series.dot` returning ``object`` dtype for :class:`ArrowDtype` and nullable-dtype data (:issue:`61375`)
719+
- Bug in :meth:`Series.std` and :meth:`Series.var` when using complex-valued data (:issue:`61645`)
719720
- Bug in ``np.matmul`` with :class:`Index` inputs raising a ``TypeError`` (:issue:`57079`)
720721

721722
Conversion

pandas/core/nanops.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1014,7 +1014,11 @@ def nanvar(
10141014
avg = _ensure_numeric(values.sum(axis=axis, dtype=np.float64)) / count
10151015
if axis is not None:
10161016
avg = np.expand_dims(avg, axis)
1017-
sqr = _ensure_numeric((avg - values) ** 2)
1017+
if values.dtype.kind == "c":
1018+
# Need to use absolute value for complex numbers.
1019+
sqr = _ensure_numeric(abs(avg - values) ** 2)
1020+
else:
1021+
sqr = _ensure_numeric((avg - values) ** 2)
10181022
if mask is not None:
10191023
np.putmask(sqr, mask, 0)
10201024
result = sqr.sum(axis=axis, dtype=np.float64) / d

pandas/tests/reductions/test_reductions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,6 +780,12 @@ def test_var_masked_array(self, ddof, exp):
780780
assert result == result_numpy_dtype
781781
assert result == exp
782782

783+
def test_var_complex_array(self):
784+
# GH#61645
785+
ser = Series([-1j, 0j, 1j], dtype=complex)
786+
assert ser.var(ddof=1) == 1.0
787+
assert ser.std(ddof=1) == 1.0
788+
783789
@pytest.mark.parametrize("dtype", ("m8[ns]", "M8[ns]", "M8[ns, UTC]"))
784790
def test_empty_timeseries_reductions_return_nat(self, dtype, skipna):
785791
# covers GH#11245

0 commit comments

Comments
 (0)