Skip to content

Commit dec5290

Browse files
REF: refactor NDFrame.interpolate to avoid dispatching to fillna (#34752)
1 parent 11271a1 commit dec5290

File tree

1 file changed

+16
-26
lines changed

1 file changed

+16
-26
lines changed

pandas/core/generic.py

+16-26
Original file line numberDiff line numberDiff line change
@@ -6888,42 +6888,33 @@ def interpolate(
68886888
inplace = validate_bool_kwarg(inplace, "inplace")
68896889

68906890
axis = self._get_axis_number(axis)
6891-
index = self._get_axis(axis)
68926891

6893-
if isinstance(self.index, MultiIndex) and method != "linear":
6892+
fillna_methods = ["ffill", "bfill", "pad", "backfill"]
6893+
should_transpose = axis == 1 and method not in fillna_methods
6894+
6895+
obj = self.T if should_transpose else self
6896+
6897+
if method not in fillna_methods:
6898+
axis = self._info_axis_number
6899+
6900+
if isinstance(obj.index, MultiIndex) and method != "linear":
68946901
raise ValueError(
68956902
"Only `method=linear` interpolation is supported on MultiIndexes."
68966903
)
68976904

6898-
# for the methods backfill, bfill, pad, ffill limit_direction and limit_area
6899-
# are being ignored, see gh-26796 for more information
6900-
if method in ["backfill", "bfill", "pad", "ffill"]:
6901-
return self.fillna(
6902-
method=method,
6903-
axis=axis,
6904-
inplace=inplace,
6905-
limit=limit,
6906-
downcast=downcast,
6907-
)
6908-
6909-
# Currently we need this to call the axis correctly inside the various
6910-
# interpolation methods
6911-
if axis == 0:
6912-
df = self
6913-
else:
6914-
df = self.T
6915-
6916-
if self.ndim == 2 and np.all(self.dtypes == np.dtype(object)):
6905+
if obj.ndim == 2 and np.all(obj.dtypes == np.dtype(object)):
69176906
raise TypeError(
69186907
"Cannot interpolate with all object-dtype columns "
69196908
"in the DataFrame. Try setting at least one "
69206909
"column to a numeric dtype."
69216910
)
69226911

6912+
# create/use the index
69236913
if method == "linear":
69246914
# prior default
6925-
index = np.arange(len(df.index))
6915+
index = np.arange(len(obj.index))
69266916
else:
6917+
index = obj.index
69276918
methods = {"index", "values", "nearest", "time"}
69286919
is_numeric_or_datetime = (
69296920
is_numeric_dtype(index.dtype)
@@ -6944,10 +6935,9 @@ def interpolate(
69446935
"has not been implemented. Try filling "
69456936
"those NaNs before interpolating."
69466937
)
6947-
data = df._mgr
6948-
new_data = data.interpolate(
6938+
new_data = obj._mgr.interpolate(
69496939
method=method,
6950-
axis=self._info_axis_number,
6940+
axis=axis,
69516941
index=index,
69526942
limit=limit,
69536943
limit_direction=limit_direction,
@@ -6958,7 +6948,7 @@ def interpolate(
69586948
)
69596949

69606950
result = self._constructor(new_data)
6961-
if axis == 1:
6951+
if should_transpose:
69626952
result = result.T
69636953
if inplace:
69646954
return self._update_inplace(result)

0 commit comments

Comments
 (0)