Skip to content

FIX: fix interpolate with kwarg limit area and limit direction using pad or bfill #31048

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
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
9afe992
Added failing test for https://github.com/pandas-dev/pandas/issues/26796
cchwala Jan 15, 2020
3a191b9
Added implementation to support `limit_area`
cchwala Jan 15, 2020
fd5d8e8
fix test
cchwala Jan 15, 2020
26d88ed
pep8
cchwala Jan 15, 2020
6597aca
fixed small error that actually had no effect since the input array `…
cchwala Jan 15, 2020
c536d3c
Raise when forbidden combination of `method` and `limit_direction` ar…
cchwala Jan 15, 2020
ed9cf21
Updated docstring with info about allowed combinations of `method` an…
cchwala Jan 15, 2020
2980325
clean up
cchwala Jan 15, 2020
ecf428e
Added entry to whatsnew file
cchwala Jan 15, 2020
f8a3423
Removed `axis` kwarg from `interpolate_1d_fill` because it was unused
cchwala Jan 15, 2020
6733186
Type annotations added to new function `interpolate_1d_fill`
cchwala Jan 15, 2020
c5b77d2
fixed incorrectly sorted imports
cchwala Jan 15, 2020
0bb36de
Added type annotation, updated docstring and removed unnecessary argu…
cchwala Feb 5, 2020
a467afd
Reverting docstring entry for default value of `limit_direction`
cchwala Feb 18, 2020
5466d8c
Moved logic for calling `missing.interpolate_1d_fill` to `missing.int…
cchwala Feb 18, 2020
3e968fc
Moved whatsnew entry to v1.1.0.rst
cchwala Feb 18, 2020
556a3cf
clean up
cchwala Feb 18, 2020
6c1e429
fixed missing Optional in type definition
cchwala Feb 18, 2020
767b0ca
small fix so that CI type validation does not complain
cchwala Mar 16, 2020
b82aaff
Merge remote-tracking branch 'upstream/master' into fix_interpolate_l…
cchwala Mar 17, 2020
26ef7b5
Apply suggestions from code review concerning list instead of set
cchwala Mar 19, 2020
b4b6b5a
added import for missing List type
cchwala Mar 19, 2020
e259549
fixed unsorted order of imports
cchwala Mar 19, 2020
8ceff58
Merge remote-tracking branch 'upstream/master' into fix_interpolate_l…
cchwala Aug 25, 2020
7c5ad7d
Added tests back in
cchwala Aug 25, 2020
92148ff
Added new solution to account for limit_area with pad
cchwala Aug 26, 2020
d62e02e
black formatting
cchwala Aug 26, 2020
c2473f2
added whatsnew entry
cchwala Aug 26, 2020
610e347
Test with moving logic for interpolate_2d with `limite_area` directly…
cchwala Sep 14, 2020
570e3c2
fix wrong arg order by using kwargs as suggested in https://github.co…
cchwala Sep 15, 2020
721304a
Added comment to explain recursion and added typing for interpolate_2d
cchwala Sep 15, 2020
73ab1bf
improved test code coverage
cchwala Sep 15, 2020
a33f629
fixed wrong typing
cchwala Sep 15, 2020
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
36 changes: 28 additions & 8 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1116,6 +1116,7 @@ def check_int_bool(self, inplace):
axis=axis,
inplace=inplace,
limit=limit,
limit_area=limit_area,
fill_value=fill_value,
coerce=coerce,
downcast=downcast,
Expand Down Expand Up @@ -1146,6 +1147,7 @@ def _interpolate_with_fill(
axis=0,
inplace=False,
limit=None,
limit_area=None,
fill_value=None,
coerce=False,
downcast=None,
Expand All @@ -1168,14 +1170,32 @@ def _interpolate_with_fill(
# We only get here for non-ExtensionBlock
fill_value = convert_scalar(self.values, fill_value)

values = missing.interpolate_2d(
values,
method=method,
axis=axis,
limit=limit,
fill_value=fill_value,
dtype=self.dtype,
)
# We have to distinguish two cases:
# 1. When kwarg `limit_area` is used: It is not
# supported by `missing.interpolate_2d()`. Using this kwarg only
# works by applying the fill along a certain axis.
# 2. All other cases: Then, `missing.interpolate_2d()` can be used.
if limit_area is not None:
def func(x):
return missing.interpolate_1d_fill(
x,
method=method,
axis=axis,
limit=limit,
limit_area=limit_area,
fill_value=fill_value,
dtype=self.dtype,
)
interp_values = np.apply_along_axis(func, axis, values)
else:
values = missing.interpolate_2d(
values,
method=method,
axis=axis,
limit=limit,
fill_value=fill_value,
dtype=self.dtype,
)

blocks = [self.make_block_same_class(values, ndim=self.ndim)]
return self._maybe_downcast(blocks, downcast)
Expand Down
146 changes: 112 additions & 34 deletions pandas/core/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,40 +222,14 @@ def interpolate_1d(
# default limit is unlimited GH #16282
limit = algos._validate_limit(nobs=None, limit=limit)

# These are sets of index pointers to invalid values... i.e. {0, 1, etc...
all_nans = set(np.flatnonzero(invalid))
start_nans = set(range(find_valid_index(yvalues, "first")))
end_nans = set(range(1 + find_valid_index(yvalues, "last"), len(valid)))
mid_nans = all_nans - start_nans - end_nans

# Like the sets above, preserve_nans contains indices of invalid values,
# but in this case, it is the final set of indices that need to be
# preserved as NaN after the interpolation.

# For example if limit_direction='forward' then preserve_nans will
# contain indices of NaNs at the beginning of the series, and NaNs that
# are more than'limit' away from the prior non-NaN.

# set preserve_nans based on direction using _interp_limit
if limit_direction == "forward":
preserve_nans = start_nans | set(_interp_limit(invalid, limit, 0))
elif limit_direction == "backward":
preserve_nans = end_nans | set(_interp_limit(invalid, 0, limit))
else:
# both directions... just use _interp_limit
preserve_nans = set(_interp_limit(invalid, limit, limit))

# if limit_area is set, add either mid or outside indices
# to preserve_nans GH #16284
if limit_area == "inside":
# preserve NaNs on the outside
preserve_nans |= start_nans | end_nans
elif limit_area == "outside":
# preserve NaNs on the inside
preserve_nans |= mid_nans

# sort preserve_nans and covert to list
preserve_nans = sorted(preserve_nans)
preserve_nans = _derive_indices_of_nans_to_preserve(
yvalues=yvalues,
valid=valid,
invalid=invalid,
limit=limit,
limit_area=limit_area,
limit_direction=limit_direction,
)

xvalues = getattr(xvalues, "values", xvalues)
yvalues = getattr(yvalues, "values", yvalues)
Expand Down Expand Up @@ -313,6 +287,51 @@ def interpolate_1d(
result[preserve_nans] = np.nan
return result

def _derive_indices_of_nans_to_preserve(
yvalues, valid, invalid, limit, limit_area, limit_direction,
):
""" Derive the indices of NaNs that shall be preserved after interpolation
This function is called by `interpolate_1d` and takes the arguments with
the same name from there. In `interpolate_1d`, after performing the
interpolation the list of indices of NaNs to preserve is used to put
NaNs in the desired locations.
"""

# These are sets of index pointers to invalid values... i.e. {0, 1, etc...
all_nans = set(np.flatnonzero(invalid))
start_nans = set(range(find_valid_index(yvalues, "first")))
end_nans = set(range(1 + find_valid_index(yvalues, "last"), len(valid)))
mid_nans = all_nans - start_nans - end_nans

# Like the sets above, preserve_nans contains indices of invalid values,
# but in this case, it is the final set of indices that need to be
# preserved as NaN after the interpolation.

# For example if limit_direction='forward' then preserve_nans will
# contain indices of NaNs at the beginning of the series, and NaNs that
# are more than'limit' away from the prior non-NaN.

# set preserve_nans based on direction using _interp_limit
if limit_direction == "forward":
preserve_nans = start_nans | set(_interp_limit(invalid, limit, 0))
elif limit_direction == "backward":
preserve_nans = end_nans | set(_interp_limit(invalid, 0, limit))
else:
# both directions... just use _interp_limit
preserve_nans = set(_interp_limit(invalid, limit, limit))

# if limit_area is set, add either mid or outside indices
# to preserve_nans GH #16284
if limit_area == "inside":
# preserve NaNs on the outside
preserve_nans |= start_nans | end_nans
elif limit_area == "outside":
# preserve NaNs on the inside
preserve_nans |= mid_nans

# sort preserve_nans and covert to list
preserve_nans = sorted(preserve_nans)
return preserve_nans

def _interpolate_scipy_wrapper(
x, y, new_x, method, fill_value=None, bounds_error=False, order=None, **kwargs
Expand Down Expand Up @@ -477,6 +496,65 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0):
else:
return [P(x, nu) for nu in der]

def interpolate_1d_fill(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you move this under interpolate_1d

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

interpolate_1d_fill is a special case needed by blocks._interpolate_with_fill() to support the limit kwargs with method pad. As you requested in the comment above interpolate_1d_fill is now called from within interpolate_2d which is what blocks._interpolate_with_fill() calls.

You request, moving it to missing.interpolate_1d will, in my opinion, not work, because missing.interpolate_1d is not reached in the call sequence for interpolating with method pad since blocks.Block.interpolate() splits up into blocks.Block._interpolate (for scipy wrappers) and blocks.Block._interpolate_with_fill (for pad methods). missing.interpolate_1d is only called in the former case, i.e. for methods using the scipy wrappers.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cchwala interpolate_2d will work on a 1d array. did you investigate applying it along an axis (with masking logic) rather than creating a 1d version.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see #34749 for alternative implementation calling interpolate_2d instead. interpolate_2d already has the limit logic so no need to use the preserve_nans set based logic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used the nice solution from #34749 as suggested above

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as a consequence there is no interpolate_1d_fill anymore

values,
method="pad",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
method="pad",
method: str = "pad",

axis=0,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
axis=0,
axis: Axis = 0,

(import from pandas._typing)

limit=None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
limit=None,
limit: Optional[int] = None,

limit_area=None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
limit_area=None,
limit_area: Optional[str] = None,

fill_value=None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fill_value=None,
fill_value: Optional[Hashable] = None,

dtype=None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
dtype=None,
dtype: Optional[Dtype] = None,

(import from pandas._typing)

):
"""
This is a 1D-versoin of `interpolate_2d`, which is used for methods `pad`
and `backfill` when interpolating. This 1D-version is necessary to be
able to handle kwarg `limit_area` via the function
` _derive_indices_of_nans_to_preserve`. It is used the same way as the
1D-interpolation functions which are based on scipy-interpolation, i.e.
via np.apply_along_axis.
"""
if method == "pad":
limit_direction = "forward"
elif method == "backfill":
limit_direction = "backward"
else:
raise ValueError("`method` must be either 'pad' or 'backfill'.")

orig_values = values

yvalues = values
invalid = isna(yvalues)
valid = ~invalid

if values.ndim > 1:
raise AssertionError("This only works with 1D data.")

if fill_value is None:
mask = None
else: # todo create faster fill func without masking
mask = mask_missing(values, fill_value)

preserve_nans = _derive_indices_of_nans_to_preserve(
yvalues=yvalues,
valid=valid,
invalid=invalid,
limit=limit,
limit_area=limit_area,
limit_direction=limit_direction,
)

method = clean_fill_method(method)
if method == "pad":
values = pad_1d(values, limit=limit, mask=mask, dtype=dtype)
else:
values = backfill_1d(values, limit=limit, mask=mask, dtype=dtype)

if orig_values.dtype.kind == "M":
# convert float back to datetime64
values = values.astype(orig_values.dtype)

values[preserve_nans] = fill_value
return values

def interpolate_2d(
values, method="pad", axis=0, limit=None, fill_value=None, dtype=None
Expand Down
55 changes: 55 additions & 0 deletions pandas/tests/series/test_missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,61 @@ def test_interp_limit_area(self):
with pytest.raises(ValueError, match=msg):
s.interpolate(method="linear", limit_area="abc")

def test_interp_limit_area_with_pad(self):
# Test for issue #26796
s = Series(
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan])

expected = Series(
[np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan])
result = s.interpolate(method="pad", limit_area="inside")
tm.assert_series_equal(result, expected)

expected = Series(
[np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan]
)
result = s.interpolate(method="pad", limit_area="inside", limit=1)
tm.assert_series_equal(result, expected)

expected = Series(
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0])
result = s.interpolate(method="pad", limit_area="outside")
tm.assert_series_equal(result, expected)

expected = Series(
[np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan]
)
result = s.interpolate(method="pad", limit_area="outside", limit=1)
tm.assert_series_equal(result, expected)

def test_interp_limit_area_with_backfill(self):
# Test for issue #26796
s = Series(
[np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan])

expected = Series(
[np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan])
result = s.interpolate(method="bfill", limit_area="inside")
tm.assert_series_equal(result, expected)

expected = Series(
[np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan]
)
result = s.interpolate(method="bfill", limit_area="inside", limit=1)
tm.assert_series_equal(result, expected)

expected = Series(
[3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan])
result = s.interpolate(method="bfill", limit_area="outside")
tm.assert_series_equal(result, expected)

expected = Series(
[np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan]
)
result = s.interpolate(method="bfill", limit_area="outside", limit=1)
tm.assert_series_equal(result, expected)


def test_interp_limit_direction(self):
# These tests are for issue #9218 -- fill NaNs in both directions.
s = Series([1, 3, np.nan, np.nan, np.nan, 11])
Expand Down