maxframe.dataframe.groupby.DataFrameGroupBy.sample#

DataFrameGroupBy.sample(n: int | None = None, frac: float | None = None, replace: bool = False, weights: Sequence | Series | None = None, random_state: RandomState | None = None, errors: str = 'ignore')#

从每个组中返回随机样本项。

您可以使用 random_state 来保证结果的可重现性。

参数:
  • n (int, optional) -- 每组要返回的项数。不能与 frac 同时使用,且除非 replace 为 True,否则不能超过最小组的大小。如果 frac 为 None,则默认值为 1。

  • frac (float, optional) -- 要返回的项的比例。不能与 n 同时使用。

  • replace (bool, default False) -- 允许或不允许对同一行进行多次采样。

  • weights (list-like, optional) -- 默认值 None 表示等概率加权。如果传入一个类列表对象,则其值必须与底层 DataFrame 或 Series 对象具有相同的长度,并将作为每组内归一化后的采样概率。值必须是非负数,并且每组中至少有一个正值元素。

  • random_state (int, array-like, BitGenerator, np.random.RandomState, optional) -- 如果为 int、array-like 或 BitGenerator (NumPy>=1.17),则为随机数生成器的种子;如果为 np.random.RandomState,则用作 numpy RandomState 对象。

  • errors ({'ignore', 'raise'}, default 'ignore') -- 如果为 ignore,当 replace 为 False 且某些组的大小小于 n 时将不会引发错误。

返回:

一个与调用者相同类型的新对象,其中包含从调用者对象中每个组内随机采样的项。

返回类型:

Series or DataFrame

参见

DataFrame.sample

从 DataFrame 对象中生成随机样本。

numpy.random.choice

从给定的一维 numpy 数组中生成随机样本。

示例

>>> import maxframe.dataframe as md
>>> df = md.DataFrame(
...     {"a": ["red"] * 2 + ["blue"] * 2 + ["black"] * 2, "b": range(6)}
... )
>>> df.execute()
       a  b
0    red  0
1    red  1
2   blue  2
3   blue  3
4  black  4
5  black  5

为列 a 中的每个不同值随机选择一行。random_state 参数可用于保证结果的可重现性:

>>> df.groupby("a").sample(n=1, random_state=1).execute()
       a  b
4  black  4
2   blue  2
1    red  1

设置 frac 来按固定比例而不是固定数量进行采样:

>>> df.groupby("a")["b"].sample(frac=0.5, random_state=2).execute()
5    5
2    2
0    0
Name: b, dtype: int64

通过设置权重来控制组内的采样概率:

>>> df.groupby("a").sample(
...     n=1,
...     weights=[1, 1, 1, 0, 0, 1],
...     random_state=1,
... ).execute()
       a  b
5  black  5
2   blue  2
0    red  0