Skip to content

Commit 2df78e8

Browse files
Backport PR #57058 on branch 2.2.x (BUG: Series.pct_change with empty Series) (#57059)
Backport PR #57058: BUG: Series.pct_change with empty Series Co-authored-by: Matthew Roeschke <[email protected]>
1 parent fb2cf0f commit 2df78e8

File tree

3 files changed

+23
-13
lines changed

3 files changed

+23
-13
lines changed

doc/source/whatsnew/v2.2.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ including other versions of pandas.
1414
Fixed regressions
1515
~~~~~~~~~~~~~~~~~
1616
- Fixed regression in :func:`merge_ordered` raising ``TypeError`` for ``fill_method="ffill"`` and ``how="left"`` (:issue:`57010`)
17+
- Fixed regression in :meth:`Series.pct_change` raising a ``ValueError`` for an empty :class:`Series` (:issue:`57056`)
1718

1819
.. ---------------------------------------------------------------------------
1920
.. _whatsnew_221.bug_fixes:

pandas/core/generic.py

+14-13
Original file line numberDiff line numberDiff line change
@@ -12126,19 +12126,20 @@ def pct_change(
1212612126
if limit is lib.no_default:
1212712127
cols = self.items() if self.ndim == 2 else [(None, self)]
1212812128
for _, col in cols:
12129-
mask = col.isna().values
12130-
mask = mask[np.argmax(~mask) :]
12131-
if mask.any():
12132-
warnings.warn(
12133-
"The default fill_method='pad' in "
12134-
f"{type(self).__name__}.pct_change is deprecated and will "
12135-
"be removed in a future version. Either fill in any "
12136-
"non-leading NA values prior to calling pct_change or "
12137-
"specify 'fill_method=None' to not fill NA values.",
12138-
FutureWarning,
12139-
stacklevel=find_stack_level(),
12140-
)
12141-
break
12129+
if len(col) > 0:
12130+
mask = col.isna().values
12131+
mask = mask[np.argmax(~mask) :]
12132+
if mask.any():
12133+
warnings.warn(
12134+
"The default fill_method='pad' in "
12135+
f"{type(self).__name__}.pct_change is deprecated and "
12136+
"will be removed in a future version. Either fill in "
12137+
"any non-leading NA values prior to calling pct_change "
12138+
"or specify 'fill_method=None' to not fill NA values.",
12139+
FutureWarning,
12140+
stacklevel=find_stack_level(),
12141+
)
12142+
break
1214212143
fill_method = "pad"
1214312144
if limit is lib.no_default:
1214412145
limit = None

pandas/tests/series/methods/test_pct_change.py

+8
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,11 @@ def test_pct_change_no_warning_na_beginning():
118118
result = ser.pct_change()
119119
expected = Series([np.nan, np.nan, np.nan, 1, 0.5])
120120
tm.assert_series_equal(result, expected)
121+
122+
123+
def test_pct_change_empty():
124+
# GH 57056
125+
ser = Series([], dtype="float64")
126+
expected = ser.copy()
127+
result = ser.pct_change(periods=0)
128+
tm.assert_series_equal(expected, result)

0 commit comments

Comments
 (0)