-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
Cythonized GroupBy Quantile #20405
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
Cythonized GroupBy Quantile #20405
Changes from 42 commits
618ec99
74871d8
7b6ca68
31aff03
4a43815
eb18823
813da81
e152dd5
7a8fefb
b4938ba
3f7d0a9
d7aec3f
e712946
72cd30e
a3c4b11
ac96526
7d439d8
3047eed
70bf89a
02eb336
7c3c349
3b9c7c4
ad8b184
b846bc2
93b122c
09308d4
1a718f2
ff062bd
bdb5089
9b55fb5
31e66fc
41a734f
67e0f00
07b0c00
86aeb4a
86b9d8d
cfa1b45
00085d0
1f02532
3c64c1f
09695f5
68cfed9
4ce1448
5e840da
7969fb6
f9a8317
464a831
4b3f9be
b996e1d
cdd8985
64f46a3
4d88e8a
1cd93dd
9ae23c1
eb99f07
94d4892
0512f37
2370129
a018570
f41cd05
21691bb
082aea3
dc5877a
7496a9b
ec013bf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
cdef enum InterpolationEnumType: | ||
INTERPOLATION_LINEAR, | ||
INTERPOLATION_LOWER, | ||
INTERPOLATION_HIGHER, | ||
INTERPOLATION_NEAREST, | ||
INTERPOLATION_MIDPOINT |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,6 +29,8 @@ class providing the base-class of operations. | |
ensure_float, is_extension_array_dtype, is_numeric_dtype, is_scalar) | ||
from pandas.core.dtypes.missing import isna, notna | ||
|
||
from pandas.api.types import ( | ||
is_datetime64_dtype, is_integer_dtype, is_object_dtype) | ||
import pandas.core.algorithms as algorithms | ||
from pandas.core.base import ( | ||
DataError, GroupByError, PandasObject, SelectionMixin, SpecificationError) | ||
|
@@ -1688,6 +1690,72 @@ def nth(self, n, dropna=None): | |
|
||
return result | ||
|
||
def quantile(self, q=0.5, interpolation='linear'): | ||
""" | ||
Return group values at the given quantile, a la numpy.percentile. | ||
|
||
Parameters | ||
---------- | ||
q : float or array-like, default 0.5 (50% quantile) | ||
0 <= q <= 1, the quantile(s) to compute | ||
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} | ||
Method to use when the desired quantile falls between two points. | ||
|
||
Returns | ||
------- | ||
Series or DataFrame | ||
Return type determined by caller of GroupBy object. | ||
|
||
See Also | ||
-------- | ||
Series.quantile : Similar method for Series | ||
DataFrame.quantile : Similar method for DataFrame | ||
numpy.percentile : NumPy method to compute qth percentile | ||
|
||
Examples | ||
-------- | ||
>>> df = pd.DataFrame( | ||
... [['foo'] * 5 + ['bar'] * 5, | ||
... [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]], | ||
... columns=['key', 'val']) | ||
>>> df | ||
WillAyd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
|
||
inferences = { # TODO (py27): replace with nonlocal | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is pretty janky I would change to do this
basically returning the state (or an empty dict) in the pre and passing it to the post There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you will have to adjust the other callers of this but shouldn't be a big deal |
||
'is_dt': False, | ||
'is_int': False | ||
} | ||
|
||
def pre_processor(vals): | ||
if is_object_dtype(vals): | ||
raise TypeError("'quantile' cannot be performed against " | ||
"'object' dtypes!") | ||
elif is_integer_dtype(vals): | ||
inferences['is_int'] = True | ||
elif is_datetime64_dtype(vals): | ||
vals = vals.astype(np.float) | ||
inferences['is_dt'] = True | ||
|
||
return vals | ||
|
||
def post_processor(vals): | ||
if inferences['is_dt']: | ||
vals = vals.astype('datetime64[ns]') | ||
elif inferences['is_int'] and interpolation in [ | ||
'lower', 'higher', 'nearest']: | ||
vals = vals.astype(np.int64) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @chris-b1 you were spot on with the issue - thanks! Is this the idiomatic way of casting back? Saw it elsewhere in the code base just not sure what implications may carry for windows |
||
|
||
return vals | ||
|
||
return self._get_cythonized_result('group_quantile', self.grouper, | ||
aggregate=True, | ||
needs_values=True, | ||
needs_mask=True, | ||
cython_dtype=np.float64, | ||
pre_processing=pre_processor, | ||
post_processing=post_processor, | ||
q=q, interpolation=interpolation) | ||
|
||
@Substitution(name='groupby') | ||
def ngroup(self, ascending=True): | ||
""" | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -696,6 +696,26 @@ def test_is_monotonic_decreasing(in_vals, out_vals): | |
|
||
# describe | ||
# -------------------------------- | ||
def test_describe(): | ||
df = DataFrame([ | ||
[1, 2, 'foo'], | ||
[1, np.nan, 'bar'], | ||
[3, np.nan, 'baz'] | ||
], columns=['A', 'B', 'C']) | ||
grp = df.groupby('A') | ||
|
||
index = pd.Index([1, 3], name='A') | ||
columns = pd.MultiIndex.from_product([ | ||
['B'], ['count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']]) | ||
|
||
expected = pd.DataFrame([ | ||
[1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0], | ||
[0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan] | ||
], index=index, columns=columns) | ||
|
||
result = grp.describe() | ||
tm.assert_frame_equal(result, expected) | ||
|
||
|
||
def test_apply_describe_bug(mframe): | ||
grouped = mframe.groupby(level='first') | ||
|
@@ -1057,6 +1077,55 @@ def test_size(df): | |
tm.assert_series_equal(df.groupby('A').size(), out) | ||
|
||
|
||
# quantile | ||
# -------------------------------- | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. side note this file is getting pretty big, maybe should split it up a bit (later) |
||
@pytest.mark.parametrize("interpolation", [ | ||
"linear", "lower", "higher", "nearest", "midpoint"]) | ||
@pytest.mark.parametrize("a_vals,b_vals", [ | ||
# Ints | ||
([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]), | ||
([1, 2, 3, 4], [4, 3, 2, 1]), | ||
([1, 2, 3, 4, 5], [4, 3, 2, 1]), | ||
# Floats | ||
([1., 2., 3., 4., 5.], [5., 4., 3., 2., 1.]), | ||
# Missing data | ||
([1., np.nan, 3., np.nan, 5.], [5., np.nan, 3., np.nan, 1.]), | ||
([np.nan, 4., np.nan, 2., np.nan], [np.nan, 4., np.nan, 2., np.nan]), | ||
# Timestamps | ||
([x for x in pd.date_range('1/1/18', freq='D', periods=5)], | ||
[x for x in pd.date_range('1/1/18', freq='D', periods=5)][::-1]), | ||
# All NA | ||
([np.nan] * 5, [np.nan] * 5), | ||
]) | ||
@pytest.mark.parametrize('q', [0, .25, .5, .75, 1]) | ||
def test_quantile(interpolation, a_vals, b_vals, q): | ||
if interpolation == 'nearest' and q == 0.5 and b_vals == [4, 3, 2, 1]: | ||
pytest.skip("Unclear numpy expectation for nearest result with " | ||
"equidistant data") | ||
|
||
a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation) | ||
b_expected = pd.Series(b_vals).quantile(q, interpolation=interpolation) | ||
|
||
df = DataFrame({ | ||
'key': ['a'] * len(a_vals) + ['b'] * len(b_vals), | ||
'val': a_vals + b_vals}) | ||
|
||
expected = DataFrame([a_expected, b_expected], columns=['val'], | ||
index=Index(['a', 'b'], name='key')) | ||
result = df.groupby('key').quantile(q, interpolation=interpolation) | ||
|
||
tm.assert_frame_equal(result, expected) | ||
|
||
|
||
def test_quantile_raises(): | ||
df = pd.DataFrame([ | ||
['foo', 'a'], ['foo', 'b'], ['foo', 'c']], columns=['key', 'val']) | ||
|
||
with pytest.raises(TypeError, message="cannot be performed against " | ||
"'object' dtypes"): | ||
df.groupby('key').quantile() | ||
|
||
|
||
# pipe | ||
# -------------------------------- | ||
|
||
|
Uh oh!
There was an error while loading. Please reload this page.