Method: Polars::Expr#sample

Defined in:
lib/polars/expr.rb

#sample(fraction: nil, with_replacement: nil, shuffle: false, seed: nil, n: nil) ⇒ Expr

Sample from this expression.

Examples:

df = Polars::DataFrame.new({"a" => [1, 2, 3]})
df.select(Polars.col("a").sample(fraction: 1.0, with_replacement: true, seed: 1))
# =>
# shape: (3, 1)
# ┌─────┐
# │ a   │
# │ --- │
# │ i64 │
# ╞═════╡
# │ 3   │
# │ 3   │
# │ 1   │
# └─────┘

Parameters:

  • fraction (Float) (defaults to: nil)

    Fraction of items to return. Cannot be used with n.

  • with_replacement (Boolean) (defaults to: nil)

    Allow values to be sampled more than once.

  • shuffle (Boolean) (defaults to: false)

    Shuffle the order of sampled data points.

  • seed (Integer) (defaults to: nil)

    Seed for the random number generator. If set to nil (default), a random seed is used.

  • n (Integer) (defaults to: nil)

    Number of items to return. Cannot be used with fraction.

Returns:



7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
# File 'lib/polars/expr.rb', line 7238

def sample(
  fraction: nil,
  with_replacement: nil,
  shuffle: false,
  seed: nil,
  n: nil
)
  # TODO update
  if with_replacement.nil?
    warn "The default `with_replacement` for `sample` method will change from `true` to `false` in a future version"
    with_replacement = true
  end

  if !n.nil? && !fraction.nil?
    raise ArgumentError, "cannot specify both `n` and `fraction`"
  end

  if !n.nil? && fraction.nil?
    n = Utils.parse_into_expression(n)
    return wrap_expr(_rbexpr.sample_n(n, with_replacement, shuffle, seed))
  end

  if fraction.nil?
    fraction = 1.0
  end
  fraction = Utils.parse_into_expression(fraction)
  wrap_expr(
    _rbexpr.sample_frac(fraction, with_replacement, shuffle, seed)
  )
end