-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
PERF/REF: groupby sample #42233
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
PERF/REF: groupby sample #42233
Changes from 12 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
5f6c210
wip
mzeitlin11 1ad13c4
Merge remote-tracking branch 'upstream/master' into gb_sample
mzeitlin11 6dc1485
WIP
mzeitlin11 45e0fe1
Add asv
mzeitlin11 e7c7d75
Avoid concat
mzeitlin11 ca26efb
Clean dead code
mzeitlin11 f147052
WIP
mzeitlin11 79e6b61
Merge remote-tracking branch 'upstream/master' into gb_sample
mzeitlin11 3834f0c
Add whatsnew, fix some typing
mzeitlin11 a702870
Add docstrings
mzeitlin11 4ff88c9
Merge remote-tracking branch 'upstream/master' into gb_sample
mzeitlin11 7fb839c
Improve some variable names
mzeitlin11 202c3c1
Merge remote-tracking branch 'upstream/master' into gb_sample
mzeitlin11 994384d
Move to sample.py
mzeitlin11 fe9b028
Add module comment
mzeitlin11 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,6 +25,7 @@ | |
AnyArrayLike, | ||
ArrayLike, | ||
DtypeObj, | ||
FrameOrSeries, | ||
FrameOrSeriesUnion, | ||
Scalar, | ||
) | ||
|
@@ -58,6 +59,7 @@ | |
) | ||
from pandas.core.dtypes.dtypes import PandasDtype | ||
from pandas.core.dtypes.generic import ( | ||
ABCDataFrame, | ||
ABCDatetimeArray, | ||
ABCExtensionArray, | ||
ABCIndex, | ||
|
@@ -1891,3 +1893,138 @@ def union_with_duplicates(lvals: ArrayLike, rvals: ArrayLike) -> ArrayLike: | |
for i, value in enumerate(unique_array): | ||
indexer += [i] * int(max(l_count[value], r_count[value])) | ||
return unique_array.take(indexer) | ||
|
||
|
||
# ------ # | ||
# sample # | ||
# ------ # | ||
|
||
|
||
def preprocess_weights(obj: FrameOrSeries, weights, axis: int) -> np.ndarray: | ||
""" | ||
Process and validate the `weights` argument to `NDFrame.sample` and | ||
`.GroupBy.sample`. | ||
|
||
Returns `weights` as an ndarray[np.float64], validated except for normalizing | ||
weights (because that must be done groupwise in groupby sampling). | ||
""" | ||
# If a series, align with frame | ||
if isinstance(weights, ABCSeries): | ||
weights = weights.reindex(obj.axes[axis]) | ||
|
||
# Strings acceptable if a dataframe and axis = 0 | ||
if isinstance(weights, str): | ||
if isinstance(obj, ABCDataFrame): | ||
if axis == 0: | ||
try: | ||
weights = obj[weights] | ||
except KeyError as err: | ||
raise KeyError( | ||
"String passed to weights not a valid column" | ||
) from err | ||
else: | ||
raise ValueError( | ||
"Strings can only be passed to " | ||
"weights when sampling from rows on " | ||
"a DataFrame" | ||
) | ||
else: | ||
raise ValueError( | ||
"Strings cannot be passed as weights when sampling from a Series." | ||
) | ||
|
||
if isinstance(obj, ABCSeries): | ||
func = obj._constructor | ||
else: | ||
func = obj._constructor_sliced | ||
|
||
weights = func(weights, dtype="float64")._values | ||
|
||
if len(weights) != obj.shape[axis]: | ||
raise ValueError("Weights and axis to be sampled must be of same length") | ||
|
||
if lib.has_infs(weights): | ||
raise ValueError("weight vector may not include `inf` values") | ||
|
||
if (weights < 0).any(): | ||
raise ValueError("weight vector many not include negative values") | ||
|
||
weights[np.isnan(weights)] = 0 | ||
return weights | ||
|
||
|
||
def process_sampling_size( | ||
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. Conditionals here were refactored for mypy (but IMO clearer to follow as well) |
||
n: int | None, frac: float | None, replace: bool | ||
) -> int | None: | ||
""" | ||
Process and validate the `n` and `frac` arguments to `NDFrame.sample` and | ||
`.GroupBy.sample`. | ||
|
||
Returns None if `frac` should be used (variable sampling sizes), otherwise returns | ||
the constant sampling size. | ||
""" | ||
# If no frac or n, default to n=1. | ||
if n is None and frac is None: | ||
n = 1 | ||
elif n is not None and frac is not None: | ||
raise ValueError("Please enter a value for `frac` OR `n`, not both") | ||
elif n is not None: | ||
if n < 0: | ||
raise ValueError( | ||
"A negative number of rows requested. Please provide `n` >= 0." | ||
) | ||
if n % 1 != 0: | ||
raise ValueError("Only integers accepted as `n` values") | ||
else: | ||
assert frac is not None # for mypy | ||
if frac > 1 and not replace: | ||
raise ValueError( | ||
"Replace has to be set to `True` when " | ||
"upsampling the population `frac` > 1." | ||
) | ||
if frac < 0: | ||
raise ValueError( | ||
"A negative number of rows requested. Please provide `frac` >= 0." | ||
) | ||
|
||
return n | ||
|
||
|
||
def sample( | ||
obj_len: int, | ||
size: int, | ||
replace: bool, | ||
weights: np.ndarray | None, | ||
random_state: np.random.RandomState, | ||
) -> np.ndarray: | ||
""" | ||
Randomly sample `size` indices in `np.arange(obj_len)` | ||
|
||
Parameters | ||
---------- | ||
obj_len : int | ||
The length of the indices being considered | ||
size : int | ||
The number of values to choose | ||
replace : bool | ||
Allow or disallow sampling of the same row more than once. | ||
weights : np.ndarray[np.float64] or None | ||
If None, equal probability weighting, otherwise weights according | ||
to the vector normalized | ||
random_state: np.random.RandomState | ||
State used for the random sampling | ||
|
||
Returns | ||
------- | ||
np.ndarray[np.intp] | ||
""" | ||
if weights is not None: | ||
weight_sum = weights.sum() | ||
if weight_sum != 0: | ||
weights = weights / weight_sum | ||
else: | ||
raise ValueError("Invalid weights: weights sum to zero") | ||
|
||
return random_state.choice(obj_len, size=size, replace=replace, p=weights).astype( | ||
np.intp, copy=False | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This was pretty much moved as is, with the only change being to convert to an
ndarray
earlier for better performance on later validation stepsThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
im really not a fan of Series/DataFrame methods living in this file. are there any other natural homes for this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
util/_validators
is almost a good fit, but while this validates, it also returns a modified input. Could go incore/common
? But still learning where everything lives, happy to move if anyone has a better locationThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
looks like this function is the only one that really depends on Series/DataFrame; could it just stay inside the NDFrame method? the others could go in e.g. core.array_algos.sample
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That would be nicer, but the issue is that the weights processing also needs to be called from groupby sample as well.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Another option would be to implement something like a core.methods directory for Series/DataFrame methods that have been refactored to their own files (e.g. describe). I think algos.SelectN might make sense in something like that
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like that idea - have moved to core/sample.py (on same level as describe) for now. If others like this organization, I can follow up moving describe and sample (and maybe others like you mention) to core/methods.