Skip to content

rolling.quantile returns an interpolated result #16216

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 15 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
15 changes: 14 additions & 1 deletion pandas/core/window.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1348,6 +1348,7 @@ def roll_quantile(ndarray[float64_t, cast=True] input, int64_t win,
bint is_variable
ndarray[int64_t] start, end
ndarray[double_t] output
double qlow, qhigh, vlow, vhigh

if quantile < 0.0 or quantile > 1.0:
raise ValueError("quantile value {0} not in [0, 1]".format(quantile))
Expand Down Expand Up @@ -1391,7 +1392,19 @@ def roll_quantile(ndarray[float64_t, cast=True] input, int64_t win,

if nobs >= minp:
idx = int(quantile * <double>(nobs - 1))
output[i] = skiplist.get(idx)

# Exactly last point
if idx == nobs - 1:
output[i] = skiplist.get(idx)

# Interpolated percentile
else:
qlow = (<double> idx) / (<double>(nobs - 1))
qhigh = (<double> (idx + 1)) / (<double>(nobs - 1))
vlow = skiplist.get(idx)
vhigh = skiplist.get(idx+1)

output[i] = vlow + (vhigh - vlow)*(quantile - qlow)/(qhigh - qlow)
else:
output[i] = NaN

Expand Down
15 changes: 13 additions & 2 deletions pandas/tests/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,18 @@ def scoreatpercentile(a, per):
values = np.sort(a, axis=0)

idx = per / 1. * (values.shape[0] - 1)
return values[int(idx)]

if int(idx) == values.shape[0] - 1:
retval = values[-1]

else:
qlow = int(idx) / (values.shape[0] - 1)
qhig = (int(idx) + 1) / (values.shape[0] - 1)
vlow = values[int(idx)]
vhig = values[int(idx + 1)]
retval = vlow + (vhig - vlow)*(per - qlow)/(qhig - qlow)
Copy link
Contributor

Choose a reason for hiding this comment

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

this will cause some lint issues


return retval

for q in qs:

Expand Down Expand Up @@ -3514,7 +3525,7 @@ def test_ragged_quantile(self):

result = df.rolling(window='2s', min_periods=1).quantile(0.5)
expected = df.copy()
expected['B'] = [0.0, 1, 1.0, 3.0, 3.0]
expected['B'] = [0.0, 1, 1.5, 3.0, 3.5]
tm.assert_frame_equal(result, expected)

def test_ragged_std(self):
Expand Down