8000 ENH: Enabled prefix, suffix, and sep to DataFrame.shift by RUTUPARNk · Pull Request #61710 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

ENH: Enabled prefix, suffix, and sep to DataFrame.shift #61710

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
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
ENH: Enabled prefix, suffix, and sep to DataFrame. shift with iterabl…
…e periods (#61696)
  • Loading branch information
RUTUPARNk committed Jun 26, 2025
commit 21bc7d87a38bf0c7268e8199f655db39b5b5b4b5
8 changes: 8 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5866,7 +5866,9 @@ def shift(
freq: Frequency | None = None,
axis: Axis = 0,
fill_value: Hashable = lib.no_default,
prefix: str | None = None,
suffix: str | None = None,
sep: str ="_",
) -> DataFrame:
if freq is not None and fill_value is not lib.no_default:
# GH#53832
Expand Down Expand Up @@ -5899,11 +5901,17 @@ def shift(
shifted_dataframes.append(
super()
.shift(periods=period, freq=freq, axis=axis, fill_value=fill_value)
.add_prefix(f"{prefix}{sep}" if prefix else "")
.add_suffix(f"{suffix}_{period}" if suffix else f"_{period}")
.rename(
columns=lambda col: col.replace(f"{sep}{sep}", sep)
)
)
return concat(shifted_dataframes, axis=1)
elif suffix:
raise ValueError("Cannot specify `suffix` if `periods` is an int.")
elif prefix:
raise ValueError("Cannot specify `prefix` if `periods` is an int.")
periods = cast(int, periods)

ncols = len(self.columns)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/frame/methods/test_shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,16 @@ def test_shift_with_iterable_check_other_arguments(self):
expected = DataFrame({"a_suffix_0": [1, 2], "a_suffix_1": [np.nan, 1.0]})
tm.assert_frame_equal(shifted, expected)

# test prefix and sep
shifted = df[["a"]].shift(shifts, prefix="pre", suffix="suf", sep="-")
expected = DataFrame(
{
"pre-a-suf-0": [1, 2],
"pre-a-suf-1": [np.nan, 1.0]
}
)
tm.assert_frame_equal(shifted, expected)

# check bad inputs when doing multiple shifts
msg = "If `periods` contains multiple shifts, `axis` cannot be 1."
with pytest.raises(ValueError, match=msg):
Expand Down
Loading
0