-
-
Notifications
You must be signed in to change notification settings - Fork 18.6k
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 all 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
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 |
---|---|---|
@@ -0,0 +1,144 @@ | ||
""" | ||
Module containing utilities for NDFrame.sample() and .GroupBy.sample() | ||
""" | ||
from __future__ import annotations | ||
|
||
import numpy as np | ||
|
||
from pandas._libs import lib | ||
from pandas._typing import FrameOrSeries | ||
|
||
from pandas.core.dtypes.generic import ( | ||
ABCDataFrame, | ||
ABCSeries, | ||
) | ||
|
||
|
||
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( | ||
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
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.
Uh oh!
There was an error while loading. Please reload this page.