Skip to content

REF: refactor NDFrame.interpolate to avoid dispatching to fillna #34752

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

Merged
Merged
Changes from all commits
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
42 changes: 16 additions & 26 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6888,42 +6888,33 @@ def interpolate(
inplace = validate_bool_kwarg(inplace, "inplace")

axis = self._get_axis_number(axis)
index = self._get_axis(axis)

if isinstance(self.index, MultiIndex) and method != "linear":
fillna_methods = ["ffill", "bfill", "pad", "backfill"]
should_transpose = axis == 1 and method not in fillna_methods

obj = self.T if should_transpose else self

if method not in fillna_methods:
axis = self._info_axis_number

if isinstance(obj.index, MultiIndex) and method != "linear":
raise ValueError(
"Only `method=linear` interpolation is supported on MultiIndexes."
)

# for the methods backfill, bfill, pad, ffill limit_direction and limit_area
# are being ignored, see gh-26796 for more information
if method in ["backfill", "bfill", "pad", "ffill"]:
return self.fillna(
method=method,
axis=axis,
inplace=inplace,
limit=limit,
downcast=downcast,
)

# Currently we need this to call the axis correctly inside the various
# interpolation methods
if axis == 0:
df = self
else:
df = self.T

if self.ndim == 2 and np.all(self.dtypes == np.dtype(object)):
if obj.ndim == 2 and np.all(obj.dtypes == np.dtype(object)):
raise TypeError(
"Cannot interpolate with all object-dtype columns "
"in the DataFrame. Try setting at least one "
"column to a numeric dtype."
)

# create/use the index
if method == "linear":
# prior default
index = np.arange(len(df.index))
index = np.arange(len(obj.index))
else:
index = obj.index
methods = {"index", "values", "nearest", "time"}
is_numeric_or_datetime = (
is_numeric_dtype(index.dtype)
Expand All @@ -6944,10 +6935,9 @@ def interpolate(
"has not been implemented. Try filling "
"those NaNs before interpolating."
)
data = df._mgr
new_data = data.interpolate(
new_data = obj._mgr.interpolate(
method=method,
axis=self._info_axis_number,
axis=axis,
index=index,
limit=limit,
limit_direction=limit_direction,
Expand All @@ -6958,7 +6948,7 @@ def interpolate(
)

result = self._constructor(new_data)
if axis == 1:
if should_transpose:
result = result.T
if inplace:
return self._update_inplace(result)
Expand Down