Class: Polars::Series

Inherits:
Object
  • Object
show all
Defined in:
lib/polars/series.rb

Overview

A Series represents a single column in a polars DataFrame.

Instance Method Summary collapse

Constructor Details

#initialize(name = nil, values = nil, dtype: nil, strict: true, nan_to_null: false, dtype_if_empty: nil) ⇒ Series

Create a new Series.

Examples:

Constructing a Series by specifying name and values positionally:

s = Polars::Series.new("a", [1, 2, 3])

Notice that the dtype is automatically inferred as a polars Int64:

s.dtype
# => Polars::Int64

Constructing a Series with a specific dtype:

s2 = Polars::Series.new("a", [1, 2, 3], dtype: :f32)

It is possible to construct a Series with values as the first positional argument. This syntax considered an anti-pattern, but it can be useful in certain scenarios. You must specify any other arguments through keywords.

s3 = Polars::Series.new([1, 2, 3])

Parameters:

  • name (String, Array, nil) (defaults to: nil)

    Name of the series. Will be used as a column name when used in a DataFrame. When not specified, name is set to an empty string.

  • values (Array, nil) (defaults to: nil)

    One-dimensional data in various forms. Supported are: Array and Series.

  • dtype (Symbol, nil) (defaults to: nil)

    Polars dtype of the Series data. If not specified, the dtype is inferred.

  • strict (Boolean) (defaults to: true)

    Throw error on numeric overflow.

  • nan_to_null (Boolean) (defaults to: false)

    Not used.

  • dtype_if_empty (Symbol, nil) (defaults to: nil)

    If no dtype is specified and values contains nil or an empty array, set the Polars dtype of the Series data. If not specified, Float32 is used.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/polars/series.rb', line 35

def initialize(name = nil, values = nil, dtype: nil, strict: true, nan_to_null: false, dtype_if_empty: nil)
  # Handle case where values are passed as the first argument
  if !name.nil? && !name.is_a?(::String)
    if values.nil?
      values = name
      name = nil
    else
      raise ArgumentError, "Series name must be a string."
    end
  end

  name = "" if name.nil?

  # TODO improve
  if values.is_a?(Range) && values.begin.is_a?(::String)
    values = values.to_a
  end

  if values.nil?
    self._s = sequence_to_rbseries(name, [], dtype: dtype, dtype_if_empty: dtype_if_empty)
  elsif values.is_a?(Series)
    self._s = series_to_rbseries(name, values)
  elsif values.is_a?(Range)
    self._s =
      Polars.arange(
        values.first,
        values.last + (values.exclude_end? ? 0 : 1),
        step: 1,
        eager: true,
        dtype: dtype
      )
      .rename(name, in_place: true)
      ._s
  elsif values.is_a?(::Array)
    self._s = sequence_to_rbseries(name, values, dtype: dtype, strict: strict, dtype_if_empty: dtype_if_empty)
  elsif defined?(Numo::NArray) && values.is_a?(Numo::NArray)
    self._s = numo_to_rbseries(name, values, strict: strict, nan_to_null: nan_to_null)

    if !dtype.nil?
      self._s = self.cast(dtype, strict: true)._s
    end
  else
    raise ArgumentError, "Series constructor called with unsupported type; got #{values.class.name}"
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Polars::ExprDispatch

Instance Method Details

#!Series

Performs boolean not.

Returns:

Raises:

  • (NotImplementedError)


408
409
410
411
412
413
# File 'lib/polars/series.rb', line 408

def !
  if dtype == Boolean
    return Utils.wrap_s(_s.not)
  end
  raise NotImplementedError
end

#!=(other) ⇒ Series

Not equal.

Returns:



191
192
193
# File 'lib/polars/series.rb', line 191

def !=(other)
  _comp(other, :neq)
end

#%(other) ⇒ Series

Returns the modulo.

Returns:



388
389
390
391
392
393
# File 'lib/polars/series.rb', line 388

def %(other)
  if is_datelike
    raise ArgumentError, "first cast to integer before applying modulo on datelike dtypes"
  end
  _arithmetic(other, :rem)
end

#&(other) ⇒ Series

Bitwise AND.

Returns:



154
155
156
157
158
159
# File 'lib/polars/series.rb', line 154

def &(other)
  if !other.is_a?(Series)
    other = Series.new([other])
  end
  Utils.wrap_s(_s.bitand(other._s))
end

#*(other) ⇒ Series

Performs multiplication.

Returns:



360
361
362
363
364
365
366
367
368
# File 'lib/polars/series.rb', line 360

def *(other)
  if is_temporal
    raise ArgumentError, "first cast to integer before multiplying datelike dtypes"
  elsif other.is_a?(DataFrame)
    other * self
  else
    _arithmetic(other, :mul)
  end
end

#**(power) ⇒ Series

Raises to the power of exponent.

Returns:



398
399
400
401
402
403
# File 'lib/polars/series.rb', line 398

def **(power)
  if is_datelike
    raise ArgumentError, "first cast to integer before raising datelike dtypes to a power"
  end
  to_frame.select(Polars.col(name).pow(power)).to_series
end

#+(other) ⇒ Series

Performs addition.

Returns:



346
347
348
# File 'lib/polars/series.rb', line 346

def +(other)
  _arithmetic(other, :add)
end

#-(other) ⇒ Series

Performs subtraction.

Returns:



353
354
355
# File 'lib/polars/series.rb', line 353

def -(other)
  _arithmetic(other, :sub)
end

#-@Series

Performs negation.

Returns:



418
419
420
# File 'lib/polars/series.rb', line 418

def -@
  0 - self
end

#/(other) ⇒ Series

Performs division.

Returns:



373
374
375
376
377
378
379
380
381
382
383
# File 'lib/polars/series.rb', line 373

def /(other)
  if is_temporal
    raise ArgumentError, "first cast to integer before dividing datelike dtypes"
  end

  if is_float
    return _arithmetic(other, :div)
  end

  cast(Float64) / other
end

#<(other) ⇒ Series

Less than.

Returns:



205
206
207
# File 'lib/polars/series.rb', line 205

def <(other)
  _comp(other, :lt)
end

#<=(other) ⇒ Series

Less than or equal.

Returns:



219
220
221
# File 'lib/polars/series.rb', line 219

def <=(other)
  _comp(other, :lt_eq)
end

#==(other) ⇒ Series

Equal.

Returns:



184
185
186
# File 'lib/polars/series.rb', line 184

def ==(other)
  _comp(other, :eq)
end

#>(other) ⇒ Series

Greater than.

Returns:



198
199
200
# File 'lib/polars/series.rb', line 198

def >(other)
  _comp(other, :gt)
end

#>=(other) ⇒ Series

Greater than or equal.

Returns:



212
213
214
# File 'lib/polars/series.rb', line 212

def >=(other)
  _comp(other, :gt_eq)
end

#[](item) ⇒ Object

Returns elements of the Series.

Returns:

Raises:

  • (ArgumentError)


436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'lib/polars/series.rb', line 436

def [](item)
  if item.is_a?(Series) && [UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64].include?(item.dtype)
    return Utils.wrap_s(_s.take_with_series(_pos_idxs(item)._s))
  end

  if item.is_a?(Series) && item.bool?
    return filter(item)
  end

  if item.is_a?(Integer)
    if item < 0
      item = len + item
    end

    return _s.get_idx(item)
  end

  if item.is_a?(Range)
    return Slice.new(self).apply(item)
  end

  if Utils.is_int_sequence(item)
    return Utils.wrap_s(_s.take_with_series(_pos_idxs(Series.new("", item))._s))
  end

  raise ArgumentError, "Cannot get item of type: #{item.class.name}"
end

#[]=(key, value) ⇒ Object

Sets an element of the Series.

Returns:



467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/polars/series.rb', line 467

def []=(key, value)
  if value.is_a?(::Array)
    if is_numeric || is_datelike
      scatter(key, value)
      return
    end
    raise ArgumentError, "cannot set Series of dtype: #{dtype} with list/tuple as value; use a scalar value"
  end

  if key.is_a?(Series)
    if key.dtype == Boolean
      self._s = set(key, value)._s
    elsif key.dtype == UInt64
      self._s = scatter(key.cast(UInt32), value)._s
    elsif key.dtype == UInt32
      self._s = scatter(key, value)._s
    else
      raise Todo
    end
  elsif key.is_a?(::Array)
    s = Utils.wrap_s(sequence_to_rbseries("", key, dtype: UInt32))
    self[s] = value
  elsif key.is_a?(Range)
    s = Series.new("", key, dtype: UInt32)
    self[s] = value
  elsif key.is_a?(Integer)
    self[[key]] = value
  else
    raise ArgumentError, "cannot use #{key} for indexing"
  end
end

#^(other) ⇒ Series

Bitwise XOR.

Returns:



174
175
176
177
178
179
# File 'lib/polars/series.rb', line 174

def ^(other)
  if !other.is_a?(Series)
    other = Series.new([other])
  end
  Utils.wrap_s(_s.bitxor(other._s))
end

#_hash(seed = 0, seed_1 = nil, seed_2 = nil, seed_3 = nil) ⇒ Series

Hash the Series.

The hash value is of type :u64.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s._hash(42)
# =>
# shape: (3,)
# Series: 'a' [u64]
# [
#         2374023516666777365
#         10386026231460783898
#         17796317186427479491
# ]

Parameters:

  • seed (Integer) (defaults to: 0)

    Random seed parameter. Defaults to 0.

  • seed_1 (Integer) (defaults to: nil)

    Random seed parameter. Defaults to seed if not set.

  • seed_2 (Integer) (defaults to: nil)

    Random seed parameter. Defaults to seed if not set.

  • seed_3 (Integer) (defaults to: nil)

    Random seed parameter. Defaults to seed if not set.

Returns:



3768
3769
3770
# File 'lib/polars/series.rb', line 3768

def _hash(seed = 0, seed_1 = nil, seed_2 = nil, seed_3 = nil)
  super
end

#absSeries

Compute absolute values.

Examples:

s = Polars::Series.new([1, -2, -3])
s.abs
# =>
# shape: (3,)
# Series: '' [i64]
# [
#         1
#         2
#         3
# ]

Returns:



3833
3834
3835
# File 'lib/polars/series.rb', line 3833

def abs
  super
end

#alias(name) ⇒ Series

Return a copy of the Series with a new alias/name.

Examples:

s = Polars::Series.new("x", [1, 2, 3])
s.alias("y")

Parameters:

Returns:



1365
1366
1367
1368
1369
# File 'lib/polars/series.rb', line 1365

def alias(name)
  s = dup
  s._s.rename(name)
  s
end

#all?(ignore_nulls: true, &block) ⇒ Boolean Also known as: all

Check if all boolean values in the column are true.

Examples:

Polars::Series.new([true, true]).all?
# => true
Polars::Series.new([false, true]).all?
# => false
Polars::Series.new([nil, true]).all?
# => true

Returns:



588
589
590
591
592
593
594
# File 'lib/polars/series.rb', line 588

def all?(ignore_nulls: true, &block)
  if block_given?
    apply(skip_nulls: ignore_nulls, &block).all?
  else
    _s.all(ignore_nulls)
  end
end

#any?(ignore_nulls: true, &block) ⇒ Boolean Also known as: any

Check if any boolean value in the column is true.

Examples:

Polars::Series.new([true, false]).any?
# => true
Polars::Series.new([false, false]).any?
# => false
Polars::Series.new([nil, false]).any?
# => false

Returns:



564
565
566
567
568
569
570
# File 'lib/polars/series.rb', line 564

def any?(ignore_nulls: true, &block)
  if block_given?
    apply(skip_nulls: ignore_nulls, &block).any?
  else
    _s.any(ignore_nulls)
  end
end

#append(other, append_chunks: true) ⇒ Series

Append a Series to this one.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s2 = Polars::Series.new("b", [4, 5, 6])
s.append(s2)
# =>
# shape: (6,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
#         4
#         5
#         6
# ]

Parameters:

  • other (Series)

    Series to append.

  • append_chunks (Boolean) (defaults to: true)

    If set to true the append operation will add the chunks from other to self. This is super cheap.

    If set to false the append operation will do the same as DataFrame#extend which extends the memory backed by this Series with the values from other.

    Different from append_chunks, extend appends the data from other to the underlying memory locations and thus may cause a reallocation (which is expensive).

    If this does not cause a reallocation, the resulting data structure will not have any extra chunks and thus will yield faster queries.

    Prefer extend over append_chunks when you want to do a query after a single append. For instance during online operations where you add n rows and rerun a query.

    Prefer append_chunks over extend when you want to append many times before doing a query. For instance, when you read in multiple files and when to store them in a single Series. In the latter case, finish the sequence of append_chunks operations with a rechunk.

Returns:



1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
# File 'lib/polars/series.rb', line 1622

def append(other, append_chunks: true)
  begin
    if append_chunks
      _s.append(other._s)
    else
      _s.extend(other._s)
    end
  rescue => e
    if e.message == "Already mutably borrowed"
      append(other.clone, append_chunks)
    else
      raise e
    end
  end
  self
end

#arccosSeries Also known as: acos

Compute the element-wise value for the inverse cosine.

Examples:

s = Polars::Series.new("a", [1.0, 0.0, -1.0])
s.arccos
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.0
#         1.570796
#         3.141593
# ]

Returns:



2973
2974
2975
# File 'lib/polars/series.rb', line 2973

def arccos
  super
end

#arccoshSeries Also known as: acosh

Compute the element-wise value for the inverse hyperbolic cosine.

Examples:

s = Polars::Series.new("a", [5.0, 1.0, 0.0, -1.0])
s.arccosh
# =>
# shape: (4,)
# Series: 'a' [f64]
# [
#         2.292432
#         0.0
#         NaN
#         NaN
# ]

Returns:



3034
3035
3036
# File 'lib/polars/series.rb', line 3034

def arccosh
  super
end

#arcsinSeries Also known as: asin

Compute the element-wise value for the inverse sine.

Examples:

s = Polars::Series.new("a", [1.0, 0.0, -1.0])
s.arcsin
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         1.570796
#         0.0
#         -1.570796
# ]

Returns:



2953
2954
2955
# File 'lib/polars/series.rb', line 2953

def arcsin
  super
end

#arcsinhSeries Also known as: asinh

Compute the element-wise value for the inverse hyperbolic sine.

Examples:

s = Polars::Series.new("a", [1.0, 0.0, -1.0])
s.arcsinh
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.881374
#         0.0
#         -0.881374
# ]

Returns:



3013
3014
3015
# File 'lib/polars/series.rb', line 3013

def arcsinh
  super
end

#arctanSeries Also known as: atan

Compute the element-wise value for the inverse tangent.

Examples:

s = Polars::Series.new("a", [1.0, 0.0, -1.0])
s.arctan
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.785398
#         0.0
#         -0.785398
# ]

Returns:



2993
2994
2995
# File 'lib/polars/series.rb', line 2993

def arctan
  super
end

#arctanhSeries Also known as: atanh

Compute the element-wise value for the inverse hyperbolic tangent.

Examples:

s = Polars::Series.new("a", [2.0, 1.0, 0.5, 0.0, -0.5, -1.0, -1.1])
s.arctanh
# =>
# shape: (7,)
# Series: 'a' [f64]
# [
#         NaN
#         inf
#         0.549306
#         0.0
#         -0.549306
#         -inf
#         NaN
# ]

Returns:



3058
3059
3060
# File 'lib/polars/series.rb', line 3058

def arctanh
  super
end

#arg_maxInteger?

Get the index of the maximal value.

Examples:

s = Polars::Series.new("a", [3, 2, 1])
s.arg_max
# => 0

Returns:

  • (Integer, nil)


1874
1875
1876
# File 'lib/polars/series.rb', line 1874

def arg_max
  _s.arg_max
end

#arg_minInteger?

Get the index of the minimal value.

Examples:

s = Polars::Series.new("a", [3, 2, 1])
s.arg_min
# => 2

Returns:

  • (Integer, nil)


1862
1863
1864
# File 'lib/polars/series.rb', line 1862

def arg_min
  _s.arg_min
end

#arg_sort(reverse: false, nulls_last: false) ⇒ Series Also known as: argsort

Get the index values that would sort this Series.

Examples:

s = Polars::Series.new("a", [5, 3, 4, 1, 2])
s.arg_sort
# =>
# shape: (5,)
# Series: 'a' [u32]
# [
#         3
#         4
#         1
#         2
#         0
# ]

Parameters:

  • reverse (Boolean) (defaults to: false)

    Sort in reverse (descending) order.

  • nulls_last (Boolean) (defaults to: false)

    Place null values last instead of first.

Returns:



1830
1831
1832
# File 'lib/polars/series.rb', line 1830

def arg_sort(reverse: false, nulls_last: false)
  super
end

#arg_trueSeries

Get index values where Boolean Series evaluate true.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
(s == 2).arg_true
# =>
# shape: (1,)
# Series: 'a' [u32]
# [
#         1
# ]

Returns:



2211
2212
2213
# File 'lib/polars/series.rb', line 2211

def arg_true
  Polars.arg_where(self, eager: true)
end

#arg_uniqueSeries

Get unique index as Series.

Examples:

s = Polars::Series.new("a", [1, 2, 2, 3])
s.arg_unique
# =>
# shape: (3,)
# Series: 'a' [u32]
# [
#         0
#         1
#         3
# ]

Returns:



1850
1851
1852
# File 'lib/polars/series.rb', line 1850

def arg_unique
  super
end

#arrArrayNameSpace

Create an object namespace of all array related methods.

Returns:



4428
4429
4430
# File 'lib/polars/series.rb', line 4428

def arr
  ArrayNameSpace.new(self)
end

#binBinaryNameSpace

Create an object namespace of all binary related methods.

Returns:



4435
4436
4437
# File 'lib/polars/series.rb', line 4435

def bin
  BinaryNameSpace.new(self)
end

#bottom_k(k: 5) ⇒ Boolean

Return the k smallest elements.

Examples:

s = Polars::Series.new("a", [2, 5, 1, 4, 3])
s.bottom_k(k: 3)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
# ]

Parameters:

  • k (Integer) (defaults to: 5)

    Number of elements to return.

Returns:



1804
1805
1806
# File 'lib/polars/series.rb', line 1804

def bottom_k(k: 5)
  super
end

#cast(dtype, strict: true) ⇒ Series

Cast between data types.

Examples:

s = Polars::Series.new("a", [true, false, true])
s.cast(:u32)
# =>
# shape: (3,)
# Series: 'a' [u32]
# [
#         1
#         0
#         1
# ]

Parameters:

  • dtype (Symbol)

    DataType to cast to

  • strict (Boolean) (defaults to: true)

    Throw an error if a cast could not be done for instance due to an overflow

Returns:



2372
2373
2374
# File 'lib/polars/series.rb', line 2372

def cast(dtype, strict: true)
  super
end

#catCatNameSpace

Create an object namespace of all categorical related methods.

Returns:



4442
4443
4444
# File 'lib/polars/series.rb', line 4442

def cat
  CatNameSpace.new(self)
end

#ceilSeries

Rounds up to the nearest integer value.

Only works on floating point Series.

Examples:

s = Polars::Series.new("a", [1.12345, 2.56789, 3.901234])
s.ceil
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         2.0
#         3.0
#         4.0
# ]

Returns:



2792
2793
2794
# File 'lib/polars/series.rb', line 2792

def ceil
  super
end

#chunk_lengthsArray

Get the length of each individual chunk.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s2 = Polars::Series.new("b", [4, 5, 6])

Concatenate Series with rechunk: true

Polars.concat([s, s2]).chunk_lengths
# => [6]

Concatenate Series with rechunk: false

Polars.concat([s, s2], rechunk: false).chunk_lengths
# => [3, 3]

Returns:



1407
1408
1409
# File 'lib/polars/series.rb', line 1407

def chunk_lengths
  _s.chunk_lengths
end

#clearedSeries

Create an empty copy of the current Series.

The copy has identical name/dtype but no data.

Examples:

s = Polars::Series.new("a", [nil, true, false])
s.cleared
# =>
# shape: (0,)
# Series: 'a' [bool]
# [
# ]

Returns:



2673
2674
2675
# File 'lib/polars/series.rb', line 2673

def cleared
  len > 0 ? limit(0) : clone
end

#clip(min_val = nil, max_val = nil) ⇒ Series

Clip (limit) the values in an array to a min and max boundary.

Only works for numerical types.

If you want to clip other dtypes, consider writing a "when, then, otherwise" expression. See Functions#when for more information.

Examples:

s = Polars::Series.new("foo", [-50, 5, nil, 50])
s.clip(1, 10)
# =>
# shape: (4,)
# Series: 'foo' [i64]
# [
#         1
#         5
#         null
#         10
# ]

Parameters:

  • min_val (Numeric) (defaults to: nil)

    Minimum value.

  • max_val (Numeric) (defaults to: nil)

    Maximum value.

Returns:



4075
4076
4077
# File 'lib/polars/series.rb', line 4075

def clip(min_val = nil, max_val = nil)
  super
end

#clip_max(max_val) ⇒ Series

Clip (limit) the values in an array to a max boundary.

Only works for numerical types.

If you want to clip other dtypes, consider writing a "when, then, otherwise" expression. See Functions#when for more information.

Parameters:

  • max_val (Numeric)

    Maximum value.

Returns:



4105
4106
4107
# File 'lib/polars/series.rb', line 4105

def clip_max(max_val)
  super
end

#clip_min(min_val) ⇒ Series

Clip (limit) the values in an array to a min boundary.

Only works for numerical types.

If you want to clip other dtypes, consider writing a "when, then, otherwise" expression. See Functions#when for more information.

Parameters:

  • min_val (Numeric)

    Minimum value.

Returns:



4090
4091
4092
# File 'lib/polars/series.rb', line 4090

def clip_min(min_val)
  super
end

#cosSeries

Compute the element-wise value for the cosine.

Examples:

s = Polars::Series.new("a", [0.0, Math::PI / 2.0, Math::PI])
s.cos
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         1.0
#         6.1232e-17
#         -1.0
# ]

Returns:



2915
2916
2917
# File 'lib/polars/series.rb', line 2915

def cos
  super
end

#coshSeries

Compute the element-wise value for the hyperbolic cosine.

Examples:

s = Polars::Series.new("a", [1.0, 0.0, -1.0])
s.cosh
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         1.543081
#         1.0
#         1.543081
# ]

Returns:



3097
3098
3099
# File 'lib/polars/series.rb', line 3097

def cosh
  super
end

#countInteger

Return the number of elements in the Series.

Examples:

s = Polars::Series.new("a", [1, 2, nil])
s.count
# => 2

Returns:

  • (Integer)


2334
2335
2336
# File 'lib/polars/series.rb', line 2334

def count
  len - null_count
end

#cum_max(reverse: false) ⇒ Series Also known as: cummax

Get an array with the cumulative max computed at every element.

Examples:

s = Polars::Series.new("a", [3, 5, 1])
s.cum_max
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         3
#         5
#         5
# ]

Parameters:

  • reverse (Boolean) (defaults to: false)

    reverse the operation.

Returns:



1498
1499
1500
# File 'lib/polars/series.rb', line 1498

def cum_max(reverse: false)
  super
end

#cum_min(reverse: false) ⇒ Series Also known as: cummin

Get an array with the cumulative min computed at every element.

Examples:

s = Polars::Series.new("a", [3, 5, 1])
s.cum_min
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         3
#         3
#         1
# ]

Parameters:

  • reverse (Boolean) (defaults to: false)

    reverse the operation.

Returns:



1475
1476
1477
# File 'lib/polars/series.rb', line 1475

def cum_min(reverse: false)
  super
end

#cum_prod(reverse: false) ⇒ Series Also known as: cumprod

Note:

Dtypes :i8, :u8, :i16, and :u16 are cast to :i64 before multiplying to prevent overflow issues.

Get an array with the cumulative product computed at every element.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.cum_prod
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         1
#         2
#         6
# ]

Parameters:

  • reverse (Boolean) (defaults to: false)

    reverse the operation.

Returns:



1525
1526
1527
# File 'lib/polars/series.rb', line 1525

def cum_prod(reverse: false)
  super
end

#cum_sum(reverse: false) ⇒ Series Also known as: cumsum

Note:

Dtypes :i8, :u8, :i16, and :u16 are cast to :i64 before summing to prevent overflow issues.

Get an array with the cumulative sum computed at every element.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.cum_sum
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         1
#         3
#         6
# ]

Parameters:

  • reverse (Boolean) (defaults to: false)

    reverse the operation.

Returns:



1452
1453
1454
# File 'lib/polars/series.rb', line 1452

def cum_sum(reverse: false)
  super
end

#cumulative_eval(expr, min_periods: 1, parallel: false) ⇒ Series

Note:

This functionality is experimental and may change without it being considered a breaking change.

Note:

This can be really slow as it can have O(n^2) complexity. Don't use this for operations that visit all elements.

Run an expression over a sliding window that increases 1 slot every iteration.

Examples:

s = Polars::Series.new("values", [1, 2, 3, 4, 5])
s.cumulative_eval(Polars.element.first - Polars.element.last ** 2)
# =>
# shape: (5,)
# Series: 'values' [i64]
# [
#         0
#         -3
#         -8
#         -15
#         -24
# ]

Parameters:

  • expr (Expr)

    Expression to evaluate

  • min_periods (Integer) (defaults to: 1)

    Number of valid values there should be in the window before the expression is evaluated. valid values = length - null_count

  • parallel (Boolean) (defaults to: false)

    Run in parallel. Don't do this in a group by or another operation that already has much parallelization.

Returns:



1351
1352
1353
# File 'lib/polars/series.rb', line 1351

def cumulative_eval(expr, min_periods: 1, parallel: false)
  super
end

#cut(breaks, labels: nil, left_closed: false, include_breaks: false) ⇒ Series

Bin continuous values into discrete categories.

Examples:

Divide the column into three categories.

s = Polars::Series.new("foo", [-2, -1, 0, 1, 2])
s.cut([-1, 1], labels: ["a", "b", "c"])
# =>
# shape: (5,)
# Series: 'foo' [cat]
# [
#         "a"
#         "a"
#         "b"
#         "b"
#         "c"
# ]

Create a DataFrame with the breakpoint and category for each value.

cut = s.cut([-1, 1], include_breaks: true).alias("cut")
s.to_frame.with_columns(cut).unnest("cut")
# =>
# shape: (5, 3)
# ┌─────┬─────────────┬────────────┐
# │ foo ┆ break_point ┆ category   │
# │ --- ┆ ---         ┆ ---        │
# │ i64 ┆ f64         ┆ cat        │
# ╞═════╪═════════════╪════════════╡
# │ -2  ┆ -1.0        ┆ (-inf, -1] │
# │ -1  ┆ -1.0        ┆ (-inf, -1] │
# │ 0   ┆ 1.0         ┆ (-1, 1]    │
# │ 1   ┆ 1.0         ┆ (-1, 1]    │
# │ 2   ┆ inf         ┆ (1, inf]   │
# └─────┴─────────────┴────────────┘

Parameters:

  • breaks (Array)

    List of unique cut points.

  • labels (Array) (defaults to: nil)

    Names of the categories. The number of labels must be equal to the number of cut points plus one.

  • left_closed (Boolean) (defaults to: false)

    Set the intervals to be left-closed instead of right-closed.

  • include_breaks (Boolean) (defaults to: false)

    Include a column with the right endpoint of the bin each observation falls in. This will change the data type of the output from a Categorical to a Struct.

Returns:



1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
# File 'lib/polars/series.rb', line 1073

def cut(breaks, labels: nil, left_closed: false, include_breaks: false)
  result = (
    to_frame
    .select(
      Polars.col(name).cut(
        breaks,
        labels: labels,
        left_closed: left_closed,
        include_breaks: include_breaks
      )
    )
    .to_series
  )

  if include_breaks
    result = result.struct.rename_fields(["break_point", "category"])
  end

  result
end

#describeDataFrame

Quick summary statistics of a series.

Series with mixed datatypes will return summary statistics for the datatype of the first value.

Examples:

series_num = Polars::Series.new([1, 2, 3, 4, 5])
series_num.describe
# =>
# shape: (6, 2)
# ┌────────────┬──────────┐
# │ statistic  ┆ value    │
# │ ---        ┆ ---      │
# │ str        ┆ f64      │
# ╞════════════╪══════════╡
# │ min        ┆ 1.0      │
# │ max        ┆ 5.0      │
# │ null_count ┆ 0.0      │
# │ mean       ┆ 3.0      │
# │ std        ┆ 1.581139 │
# │ count      ┆ 5.0      │
# └────────────┴──────────┘
series_str = Polars::Series.new(["a", "a", nil, "b", "c"])
series_str.describe
# =>
# shape: (3, 2)
# ┌────────────┬───────┐
# │ statistic  ┆ value │
# │ ---        ┆ ---   │
# │ str        ┆ i64   │
# ╞════════════╪═══════╡
# │ unique     ┆ 4     │
# │ null_count ┆ 1     │
# │ count      ┆ 5     │
# └────────────┴───────┘

Returns:



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/polars/series.rb', line 795

def describe
  if len == 0
    raise ArgumentError, "Series must contain at least one value"
  elsif is_numeric
    s = cast(:f64)
    stats = {
      "min" => s.min,
      "max" => s.max,
      "null_count" => s.null_count,
      "mean" => s.mean,
      "std" => s.std,
      "count" => s.len
    }
  elsif is_boolean
    stats = {
      "sum" => sum,
      "null_count" => null_count,
      "count" => len
    }
  elsif is_utf8
    stats = {
      "unique" => unique.length,
      "null_count" => null_count,
      "count" => len
    }
  elsif is_datelike
    # we coerce all to string, because a polars column
    # only has a single dtype and dates: datetime and count: int don't match
    stats = {
      "min" => dt.min.to_s,
      "max" => dt.max.to_s,
      "null_count" => null_count.to_s,
      "count" => len.to_s
    }
  else
    raise TypeError, "This type is not supported"
  end

  Polars::DataFrame.new(
    {"statistic" => stats.keys, "value" => stats.values}
  )
end

#diff(n: 1, null_behavior: "ignore") ⇒ Series

Calculate the n-th discrete difference.

Examples:

s = Polars::Series.new("s", [20, 10, 30, 25, 35], dtype: Polars::Int8)
s.diff
# =>
# shape: (5,)
# Series: 's' [i8]
# [
#         null
#         -10
#         20
#         -5
#         10
# ]
s.diff(n: 2)
# =>
# shape: (5,)
# Series: 's' [i8]
# [
#         null
#         null
#         10
#         15
#         5
# ]
s.diff(n: 2, null_behavior: "drop")
# =>
# shape: (3,)
# Series: 's' [i8]
# [
#         10
#         15
#         5
# ]

Parameters:

  • n (Integer) (defaults to: 1)

    Number of slots to shift.

  • null_behavior ("ignore", "drop") (defaults to: "ignore")

    How to handle null values.

Returns:



3941
3942
3943
# File 'lib/polars/series.rb', line 3941

def diff(n: 1, null_behavior: "ignore")
  super
end

#dot(other) ⇒ Numeric

Compute the dot/inner product between two Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s2 = Polars::Series.new("b", [4.0, 5.0, 6.0])
s.dot(s2)
# => 32.0

Parameters:

  • other (Object)

    Series (or array) to compute dot product with.

Returns:

  • (Numeric)


2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
# File 'lib/polars/series.rb', line 2830

def dot(other)
  if !other.is_a?(Series)
    other = Series.new(other)
  end
  if len != other.len
    n, m = len, other.len
    raise ArgumentError, "Series length mismatch: expected #{n}, found #{m}"
  end
  _s.dot(other._s)
end

#drop_nansSeries

Drop NaN values.

Examples:

s = Polars::Series.new([1.0, nil, 3.0, Float::NAN])
s.drop_nans
# =>
# shape: (3,)
# Series: '' [f64]
# [
#         1.0
#         null
#         3.0
# ]

Returns:



715
716
717
# File 'lib/polars/series.rb', line 715

def drop_nans
  super
end

#drop_nullsSeries

Create a new Series that copies data from this Series without null values.

Examples:

s = Polars::Series.new([1.0, nil, 3.0, Float::NAN])
s.drop_nulls
# =>
# shape: (3,)
# Series: '' [f64]
# [
#         1.0
#         3.0
#         NaN
# ]

Returns:



696
697
698
# File 'lib/polars/series.rb', line 696

def drop_nulls
  super
end

#dtDateTimeNameSpace

Create an object namespace of all datetime related methods.

Returns:



4449
4450
4451
# File 'lib/polars/series.rb', line 4449

def dt
  DateTimeNameSpace.new(self)
end

#dtypeSymbol

Get the data type of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.dtype
# => Polars::Int64

Returns:

  • (Symbol)


96
97
98
# File 'lib/polars/series.rb', line 96

def dtype
  _s.dtype
end

#eachObject

Returns an enumerator.

Returns:



425
426
427
428
429
430
431
# File 'lib/polars/series.rb', line 425

def each
  return to_enum(:each) unless block_given?

  length.times do |i|
    yield self[i]
  end
end

#entropy(base: Math::E, normalize: false) ⇒ Float?

Computes the entropy.

Uses the formula -sum(pk * log(pk) where pk are discrete probabilities.

Examples:

a = Polars::Series.new([0.99, 0.005, 0.005])
a.entropy(normalize: true)
# => 0.06293300616044681
b = Polars::Series.new([0.65, 0.10, 0.25])
b.entropy(normalize: true)
# => 0.8568409950394724

Parameters:

  • base (Float) (defaults to: Math::E)

    Given base, defaults to e

  • normalize (Boolean) (defaults to: false)

    Normalize pk if it doesn't sum to 1.

Returns:

  • (Float, nil)


1313
1314
1315
# File 'lib/polars/series.rb', line 1313

def entropy(base: Math::E, normalize: false)
  Polars.select(Polars.lit(self).entropy(base: base, normalize: normalize)).to_series[0]
end

#eq(other) ⇒ Series

Method equivalent of operator expression series == other.

Returns:



240
241
242
# File 'lib/polars/series.rb', line 240

def eq(other)
  self == other
end

#eq_missing(other) ⇒ Object

Method equivalent of equality operator series == other where nil == nil.

This differs from the standard ne where null values are propagated.

Examples:

s1 = Polars::Series.new("a", [333, 200, nil])
s2 = Polars::Series.new("a", [100, 200, nil])
s1.eq(s2)
# =>
# shape: (3,)
# Series: 'a' [bool]
# [
#         false
#         true
#         null
# ]
s1.eq_missing(s2)
# =>
# shape: (3,)
# Series: 'a' [bool]
# [
#         false
#         true
#         true
# ]

Parameters:

  • other (Object)

    A literal or expression value to compare with.

Returns:



276
277
278
279
280
281
# File 'lib/polars/series.rb', line 276

def eq_missing(other)
  if other.is_a?(Expr)
    return Polars.lit(self).eq_missing(other)
  end
  to_frame.select(Polars.col(name).eq_missing(other)).to_series
end

#equals(other, strict: false, check_names: false, null_equal: false) ⇒ Boolean Also known as: series_equal

Check if series is equal with another Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s2 = Polars::Series.new("b", [4, 5, 6])
s.equals(s)
# => true
s.equals(s2)
# => false

Parameters:

  • other (Series)

    Series to compare with.

  • strict (Boolean) (defaults to: false)

    Require data types to match.

  • check_names (Boolean) (defaults to: false)

    Require names to match.

  • null_equal (Boolean) (defaults to: false)

    Consider null values as equal.

Returns:



2321
2322
2323
# File 'lib/polars/series.rb', line 2321

def equals(other, strict: false, check_names: false, null_equal: false)
  _s.equals(other._s, strict, check_names, null_equal)
end

#estimated_size(unit = "b") ⇒ Numeric

Return an estimation of the total (heap) allocated size of the Series.

Estimated size is given in the specified unit (bytes by default).

This estimation is the sum of the size of its buffers, validity, including nested arrays. Multiple arrays may share buffers and bitmaps. Therefore, the size of 2 arrays is not the sum of the sizes computed from this function. In particular, StructArray's size is an upper bound.

When an array is sliced, its allocated size remains constant because the buffer unchanged. However, this function will yield a smaller number. This is because this function returns the visible size of the buffer, not its total capacity.

FFI buffers are included in this estimation.

Examples:

s = Polars::Series.new("values", 1..1_000_000, dtype: :u32)
s.estimated_size
# => 4000000
s.estimated_size("mb")
# => 3.814697265625

Parameters:

  • unit ("b", "kb", "mb", "gb", "tb") (defaults to: "b")

    Scale the returned size to the given unit.

Returns:

  • (Numeric)


525
526
527
528
# File 'lib/polars/series.rb', line 525

def estimated_size(unit = "b")
  sz = _s.estimated_size
  Utils.scale_bytes(sz, to: unit)
end

#ewm_mean(com: nil, span: nil, half_life: nil, alpha: nil, adjust: true, min_periods: 1, ignore_nulls: true) ⇒ Series

Exponentially-weighted moving average.

Examples:

s = Polars::Series.new([1, 2, 3])
s.ewm_mean(com: 1, ignore_nulls: false)
# =>
# shape: (3,)
# Series: '' [f64]
# [
#         1.0
#         1.666667
#         2.428571
# ]

Returns:



4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
# File 'lib/polars/series.rb', line 4258

def ewm_mean(
  com: nil,
  span: nil,
  half_life: nil,
  alpha: nil,
  adjust: true,
  min_periods: 1,
  ignore_nulls: true
)
  super
end

#ewm_std(com: nil, span: nil, half_life: nil, alpha: nil, adjust: true, bias: false, min_periods: 1, ignore_nulls: true) ⇒ Series

Exponentially-weighted moving standard deviation.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.ewm_std(com: 1, ignore_nulls: false)
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.0
#         0.707107
#         0.963624
# ]

Returns:



4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
# File 'lib/polars/series.rb', line 4285

def ewm_std(
  com: nil,
  span: nil,
  half_life: nil,
  alpha: nil,
  adjust: true,
  bias: false,
  min_periods: 1,
  ignore_nulls: true
)
  super
end

#ewm_var(com: nil, span: nil, half_life: nil, alpha: nil, adjust: true, bias: false, min_periods: 1, ignore_nulls: true) ⇒ Series

Exponentially-weighted moving variance.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.ewm_var(com: 1, ignore_nulls: false)
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.0
#         0.5
#         0.928571
# ]

Returns:



4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
# File 'lib/polars/series.rb', line 4313

def ewm_var(
  com: nil,
  span: nil,
  half_life: nil,
  alpha: nil,
  adjust: true,
  bias: false,
  min_periods: 1,
  ignore_nulls: true
)
  super
end

#expSeries

Compute the exponential, element-wise.

Examples:

s = Polars::Series.new([1, 2, 3])
s.exp
# =>
# shape: (3,)
# Series: '' [f64]
# [
#         2.718282
#         7.389056
#         20.085537
# ]

Returns:



677
678
679
# File 'lib/polars/series.rb', line 677

def exp
  super
end

#explodeSeries

Explode a list or utf8 Series.

This means that every item is expanded to a new row.

Examples:

s = Polars::Series.new("a", [[1, 2], [3, 4], [9, 10]])
s.explode
# =>
# shape: (6,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
#         4
#         9
#         10
# ]

Returns:



2297
2298
2299
# File 'lib/polars/series.rb', line 2297

def explode
  super
end

#extend_constant(value, n) ⇒ Series

Extend the Series with given number of values.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.extend_constant(99, 2)
# =>
# shape: (5,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
#         99
#         99
# ]

Parameters:

  • value (Object)

    The value to extend the Series with. This value may be nil to fill with nulls.

  • n (Integer)

    The number of values to extend.

Returns:



4349
4350
4351
# File 'lib/polars/series.rb', line 4349

def extend_constant(value, n)
  Utils.wrap_s(_s.extend_constant(value, n))
end

#fill_nan(fill_value) ⇒ Series

Fill floating point NaN value with a fill value.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, Float::NAN])
s.fill_nan(0)
# =>
# shape: (4,)
# Series: 'a' [f64]
# [
#         1.0
#         2.0
#         3.0
#         0.0
# ]

Parameters:

  • fill_value (Object)

    Value used to fill nan values.

Returns:



2698
2699
2700
# File 'lib/polars/series.rb', line 2698

def fill_nan(fill_value)
  super
end

#fill_null(value = nil, strategy: nil, limit: nil) ⇒ Series

Fill null values using the specified value or strategy.

Examples:

s = Polars::Series.new("a", [1, 2, 3, nil])
s.fill_null(strategy: "forward")
# =>
# shape: (4,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
#         3
# ]
s.fill_null(strategy: "min")
# =>
# shape: (4,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
#         1
# ]
s = Polars::Series.new("b", ["x", nil, "z"])
s.fill_null(Polars.lit(""))
# =>
# shape: (3,)
# Series: 'b' [str]
# [
#         "x"
#         ""
#         "z"
# ]

Parameters:

  • value (Object) (defaults to: nil)

    Value used to fill null values.

  • strategy (nil, "forward", "backward", "min", "max", "mean", "zero", "one") (defaults to: nil)

    Strategy used to fill null values.

  • limit (defaults to: nil)

    Number of consecutive null values to fill when using the "forward" or "backward" strategy.

Returns:



2750
2751
2752
# File 'lib/polars/series.rb', line 2750

def fill_null(value = nil, strategy: nil, limit: nil)
  super
end

#filter(predicate) ⇒ Series

Filter elements by a boolean mask.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
mask = Polars::Series.new("", [true, false, true])
s.filter(mask)
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         1
#         3
# ]

Parameters:

Returns:



1657
1658
1659
1660
1661
1662
# File 'lib/polars/series.rb', line 1657

def filter(predicate)
  if predicate.is_a?(::Array)
    predicate = Series.new("", predicate)
  end
  Utils.wrap_s(_s.filter(predicate._s))
end

#flagsHash

Get flags that are set on the Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.flags
# => {"SORTED_ASC"=>false, "SORTED_DESC"=>false}

Returns:

  • (Hash)


108
109
110
111
112
113
114
115
116
117
# File 'lib/polars/series.rb', line 108

def flags
  out = {
    "SORTED_ASC" => _s.is_sorted_flag,
    "SORTED_DESC" => _s.is_sorted_reverse_flag
  }
  if dtype.is_a?(List)
    out["FAST_EXPLODE"] = _s.can_fast_explode_flag
  end
  out
end

#floorSeries

Rounds down to the nearest integer value.

Only works on floating point Series.

Examples:

s = Polars::Series.new("a", [1.12345, 2.56789, 3.901234])
s.floor
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         1.0
#         2.0
#         3.0
# ]

Returns:



2771
2772
2773
# File 'lib/polars/series.rb', line 2771

def floor
  Utils.wrap_s(_s.floor)
end

#ge(other) ⇒ Series

Method equivalent of operator expression series >= other.

Returns:



332
333
334
# File 'lib/polars/series.rb', line 332

def ge(other)
  self >= other
end

#gt(other) ⇒ Series

Method equivalent of operator expression series > other.

Returns:



339
340
341
# File 'lib/polars/series.rb', line 339

def gt(other)
  self > other
end

#has_nullsBoolean Also known as: has_validity

Return true if the Series has a validity bitmask.

If there is none, it means that there are no null values. Use this to swiftly assert a Series does not have null values.

Examples:

s = Polars::Series.new([1, 2, nil])
s.has_nulls
# => true
s[...2].has_nulls
# => false

Returns:



2009
2010
2011
# File 'lib/polars/series.rb', line 2009

def has_nulls
  _s.has_nulls
end

#head(n = 10) ⇒ Series

Get the first n rows.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.head(2)
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         1
#         2
# ]

Parameters:

  • n (Integer) (defaults to: 10)

    Number of rows to return.

Returns:



1681
1682
1683
# File 'lib/polars/series.rb', line 1681

def head(n = 10)
  to_frame.select(F.col(name).head(n)).to_series
end

#interpolate(method: "linear") ⇒ Series

Interpolate intermediate values. The interpolation method is linear.

Examples:

s = Polars::Series.new("a", [1, 2, nil, nil, 5])
s.interpolate
# =>
# shape: (5,)
# Series: 'a' [f64]
# [
#         1.0
#         2.0
#         3.0
#         4.0
#         5.0
# ]

Returns:



3814
3815
3816
# File 'lib/polars/series.rb', line 3814

def interpolate(method: "linear")
  super
end

#is_booleanBoolean Also known as: boolean?, is_bool, bool?

Check if this Series is a Boolean.

Examples:

s = Polars::Series.new("a", [true, false, true])
s.is_boolean
# => true

Returns:



2523
2524
2525
# File 'lib/polars/series.rb', line 2523

def is_boolean
  dtype == Boolean
end

#is_datelikeBoolean Also known as: datelike?, is_temporal, temporal?

Check if this Series datatype is datelike.

Examples:

s = Polars::Series.new([Date.new(2021, 1, 1), Date.new(2021, 1, 2), Date.new(2021, 1, 3)])
s.is_datelike
# => true

Returns:



2495
2496
2497
# File 'lib/polars/series.rb', line 2495

def is_datelike
  [Date, Time].include?(dtype) || dtype.is_a?(Datetime) || dtype.is_a?(Duration)
end

#is_duplicatedSeries

Get mask of all duplicated values.

Examples:

s = Polars::Series.new("a", [1, 2, 2, 3])
s.is_duplicated
# =>
# shape: (4,)
# Series: 'a' [bool]
# [
#         false
#         true
#         true
#         false
# ]

Returns:



2273
2274
2275
# File 'lib/polars/series.rb', line 2273

def is_duplicated
  super
end

#is_emptyBoolean Also known as: empty?

Check if the Series is empty.

Examples:

s = Polars::Series.new("a", [])
s.is_empty
# => true

Returns:



2022
2023
2024
# File 'lib/polars/series.rb', line 2022

def is_empty
  len == 0
end

#is_finiteSeries

Returns a boolean Series indicating which values are finite.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, Float::INFINITY])
s.is_finite
# =>
# shape: (3,)
# Series: 'a' [bool]
# [
#         true
#         true
#         false
# ]

Returns:



2082
2083
2084
# File 'lib/polars/series.rb', line 2082

def is_finite
  super
end

#is_first_distinctSeries Also known as: is_first

Get a mask of the first unique value.

Examples:

s = Polars::Series.new([1, 1, 2, 3, 2])
s.is_first_distinct
# =>
# shape: (5,)
# Series: '' [bool]
# [
#         true
#         false
#         true
#         true
#         false
# ]

Returns:



2252
2253
2254
# File 'lib/polars/series.rb', line 2252

def is_first_distinct
  super
end

#is_floatBoolean Also known as: float?

Check if this Series has floating point numbers.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0])
s.is_float
# => true

Returns:



2510
2511
2512
# File 'lib/polars/series.rb', line 2510

def is_float
  [Float32, Float64].include?(dtype)
end

#is_in(other) ⇒ Series Also known as: in?

Check if elements of this Series are in the other Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s2 = Polars::Series.new("b", [2, 4])
s2.is_in(s)
# =>
# shape: (2,)
# Series: 'b' [bool]
# [
#         true
#         false
# ]
sets = Polars::Series.new("sets", [[1, 2, 3], [1, 2], [9, 10]])
# =>
# shape: (3,)
# Series: 'sets' [list[i64]]
# [
#         [1, 2, 3]
#         [1, 2]
#         [9, 10]
# ]
optional_members = Polars::Series.new("optional_members", [1, 2, 3])
# =>
# shape: (3,)
# Series: 'optional_members' [i64]
# [
#         1
#         2
#         3
# ]
optional_members.is_in(sets)
# =>
# shape: (3,)
# Series: 'optional_members' [bool]
# [
#         true
#         true
#         false
# ]

Returns:



2193
2194
2195
# File 'lib/polars/series.rb', line 2193

def is_in(other)
  super
end

#is_infiniteSeries

Returns a boolean Series indicating which values are infinite.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, Float::INFINITY])
s.is_infinite
# =>
# shape: (3,)
# Series: 'a' [bool]
# [
#         false
#         false
#         true
# ]

Returns:



2101
2102
2103
# File 'lib/polars/series.rb', line 2101

def is_infinite
  super
end

#is_nanSeries

Returns a boolean Series indicating which values are NaN.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, Float::NAN])
s.is_nan
# =>
# shape: (4,)
# Series: 'a' [bool]
# [
#         false
#         false
#         false
#         true
# ]

Returns:



2121
2122
2123
# File 'lib/polars/series.rb', line 2121

def is_nan
  super
end

#is_not_nanSeries

Returns a boolean Series indicating which values are not NaN.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, Float::NAN])
s.is_not_nan
# =>
# shape: (4,)
# Series: 'a' [bool]
# [
#         true
#         true
#         true
#         false
# ]

Returns:



2141
2142
2143
# File 'lib/polars/series.rb', line 2141

def is_not_nan
  super
end

#is_not_nullSeries

Returns a boolean Series indicating which values are not null.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, nil])
s.is_not_null
# =>
# shape: (4,)
# Series: 'a' [bool]
# [
#         true
#         true
#         true
#         false
# ]

Returns:



2063
2064
2065
# File 'lib/polars/series.rb', line 2063

def is_not_null
  super
end

#is_nullSeries

Returns a boolean Series indicating which values are null.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, nil])
s.is_null
# =>
# shape: (4,)
# Series: 'a' [bool]
# [
#         false
#         false
#         false
#         true
# ]

Returns:



2043
2044
2045
# File 'lib/polars/series.rb', line 2043

def is_null
  super
end

#is_numericBoolean Also known as: numeric?

Check if this Series datatype is numeric.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.is_numeric
# => true

Returns:



2482
2483
2484
# File 'lib/polars/series.rb', line 2482

def is_numeric
  [Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64].include?(dtype)
end

#is_uniqueSeries

Get mask of all unique values.

Examples:

s = Polars::Series.new("a", [1, 2, 2, 3])
s.is_unique
# =>
# shape: (4,)
# Series: 'a' [bool]
# [
#         true
#         false
#         false
#         true
# ]

Returns:



2231
2232
2233
# File 'lib/polars/series.rb', line 2231

def is_unique
  super
end

#is_utf8Boolean Also known as: utf8?

Check if this Series datatype is a Utf8.

Examples:

s = Polars::Series.new("x", ["a", "b", "c"])
s.is_utf8
# => true

Returns:



2538
2539
2540
# File 'lib/polars/series.rb', line 2538

def is_utf8
  dtype == String
end

#kurtosis(fisher: true, bias: true) ⇒ Float?

Compute the kurtosis (Fisher or Pearson) of a dataset.

Kurtosis is the fourth central moment divided by the square of the variance. If Fisher's definition is used, then 3.0 is subtracted from the result to give 0.0 for a normal distribution. If bias is false, then the kurtosis is calculated using k statistics to eliminate bias coming from biased moment estimators

Examples:

s = Polars::Series.new("grades", [66, 79, 54, 97, 96, 70, 69, 85, 93, 75])
s.kurtosis
# => -1.0522623626787952
s.kurtosis(fisher: false)
# => 1.9477376373212048
s.kurtosis(fisher: false, bias: false)
# => 2.1040361802642726

Parameters:

  • fisher (Boolean) (defaults to: true)

    If true, Fisher's definition is used (normal ==> 0.0). If false, Pearson's definition is used (normal ==> 3.0).

  • bias (Boolean) (defaults to: true)

    If false, the calculations are corrected for statistical bias.

Returns:

  • (Float, nil)


4045
4046
4047
# File 'lib/polars/series.rb', line 4045

def kurtosis(fisher: true, bias: true)
  _s.kurtosis(fisher, bias)
end

#le(other) ⇒ Series

Method equivalent of operator expression series <= other.

Returns:



226
227
228
# File 'lib/polars/series.rb', line 226

def le(other)
  self <= other
end

#lenInteger Also known as: length, size

Return the number of elements in the Series.

Examples:

s = Polars::Series.new("a", [1, 2, nil])
s.len
# => 3

Returns:

  • (Integer)


2346
2347
2348
# File 'lib/polars/series.rb', line 2346

def len
  _s.len
end

#limit(n = 10) ⇒ Series

Get the first n rows.

Alias for #head.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.limit(2)
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         1
#         2
# ]

Parameters:

  • n (Integer) (defaults to: 10)

    Number of rows to return.

Returns:



1549
1550
1551
# File 'lib/polars/series.rb', line 1549

def limit(n = 10)
  to_frame.select(F.col(name).limit(n)).to_series
end

#listListNameSpace

Create an object namespace of all list related methods.

Returns:



4421
4422
4423
# File 'lib/polars/series.rb', line 4421

def list
  ListNameSpace.new(self)
end

#log(base = Math::E) ⇒ Series

Compute the logarithm to a given base.

Examples:

s = Polars::Series.new([1, 2, 3])
s.log
# =>
# shape: (3,)
# Series: '' [f64]
# [
#         0.0
#         0.693147
#         1.098612
# ]

Parameters:

  • base (Float) (defaults to: Math::E)

    Given base, defaults to Math::E.

Returns:



639
640
641
# File 'lib/polars/series.rb', line 639

def log(base = Math::E)
  super
end

#log10Series

Compute the base 10 logarithm of the input array, element-wise.

Examples:

s = Polars::Series.new([10, 100, 1000])
s.log10
# =>
# shape: (3,)
# Series: '' [f64]
# [
#         1.0
#         2.0
#         3.0
# ]

Returns:



658
659
660
# File 'lib/polars/series.rb', line 658

def log10
  super
end

#lt(other) ⇒ Series

Method equivalent of operator expression series < other.

Returns:



233
234
235
# File 'lib/polars/series.rb', line 233

def lt(other)
  self < other
end

#map_elements(return_dtype: nil, skip_nulls: true, &func) ⇒ Series Also known as: map, apply

Apply a custom/user-defined function (UDF) over elements in this Series and return a new Series.

If the function returns another datatype, the return_dtype arg should be set, otherwise the method will fail.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.map_elements { |x| x + 10 }
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         11
#         12
#         13
# ]

Parameters:

  • return_dtype (Symbol) (defaults to: nil)

    Output datatype. If none is given, the same datatype as this Series will be used.

  • skip_nulls (Boolean) (defaults to: true)

    Nulls will be skipped and not passed to the Ruby function. This is faster because Ruby can be skipped and because we call more specialized functions.

Returns:



3147
3148
3149
3150
3151
3152
3153
3154
# File 'lib/polars/series.rb', line 3147

def map_elements(return_dtype: nil, skip_nulls: true, &func)
  if return_dtype.nil?
    pl_return_dtype = nil
  else
    pl_return_dtype = Utils.rb_type_to_dtype(return_dtype)
  end
  Utils.wrap_s(_s.apply_lambda(func, pl_return_dtype, skip_nulls))
end

#maxObject

Get the maximum value in this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.max
# => 3

Returns:



898
899
900
# File 'lib/polars/series.rb', line 898

def max
  _s.max
end

#meanFloat?

Reduce this Series to the mean value.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.mean
# => 2.0

Returns:

  • (Float, nil)


862
863
864
# File 'lib/polars/series.rb', line 862

def mean
  _s.mean
end

#medianFloat?

Get the median of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.median
# => 2.0

Returns:

  • (Float, nil)


984
985
986
# File 'lib/polars/series.rb', line 984

def median
  _s.median
end

#minObject

Get the minimal value in this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.min
# => 1

Returns:



886
887
888
# File 'lib/polars/series.rb', line 886

def min
  _s.min
end

#modeSeries

Compute the most occurring value(s).

Can return multiple Values.

Examples:

s = Polars::Series.new("a", [1, 2, 2, 3])
s.mode
# =>
# shape: (1,)
# Series: 'a' [i64]
# [
#         2
# ]

Returns:



2856
2857
2858
# File 'lib/polars/series.rb', line 2856

def mode
  super
end

#n_chunksInteger

Get the number of chunks that this Series contains.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s2 = Polars::Series.new("b", [4, 5, 6])

Concatenate Series with rechunk: true

Polars.concat([s, s2]).n_chunks
# => 1

Concatenate Series with rechunk: false

Polars.concat([s, s2], rechunk: false).n_chunks
# => 2

Returns:

  • (Integer)


1426
1427
1428
# File 'lib/polars/series.rb', line 1426

def n_chunks
  _s.n_chunks
end

#n_uniqueInteger

Count the number of unique values in this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 2, 3])
s.n_unique
# => 3

Returns:

  • (Integer)


3721
3722
3723
# File 'lib/polars/series.rb', line 3721

def n_unique
  _s.n_unique
end

#nameString

Get the name of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.name
# => "a"

Returns:



127
128
129
# File 'lib/polars/series.rb', line 127

def name
  _s.name
end

#nan_maxObject

Get maximum value, but propagate/poison encountered NaN values.

Examples:

s = Polars::Series.new("a", [1, 3, 4])
s.nan_max
# => 4
s = Polars::Series.new("a", [1.0, Float::NAN, 4.0])
s.nan_max
# => NaN

Returns:



915
916
917
# File 'lib/polars/series.rb', line 915

def nan_max
  to_frame.select(F.col(name).nan_max)[0, 0]
end

#nan_minObject

Get minimum value, but propagate/poison encountered NaN values.

Examples:

s = Polars::Series.new("a", [1, 3, 4])
s.nan_min
# => 1
s = Polars::Series.new("a", [1.0, Float::NAN, 4.0])
s.nan_min
# => NaN

Returns:



932
933
934
# File 'lib/polars/series.rb', line 932

def nan_min
  to_frame.select(F.col(name).nan_min)[0, 0]
end

#ne(other) ⇒ Series

Method equivalent of operator expression series != other.

Returns:



286
287
288
# File 'lib/polars/series.rb', line 286

def ne(other)
  self != other
end

#ne_missing(other) ⇒ Object

Method equivalent of equality operator series != other where None == None.

This differs from the standard ne where null values are propagated.

Examples:

s1 = Polars::Series.new("a", [333, 200, nil])
s2 = Polars::Series.new("a", [100, 200, nil])
s1.ne(s2)
# =>
# shape: (3,)
# Series: 'a' [bool]
# [
#         true
#         false
#         null
# ]
s1.ne_missing(s2)
# =>
# shape: (3,)
# Series: 'a' [bool]
# [
#         true
#         false
#         false
# ]

Parameters:

  • other (Object)

    A literal or expression value to compare with.

Returns:



322
323
324
325
326
327
# File 'lib/polars/series.rb', line 322

def ne_missing(other)
  if other.is_a?(Expr)
    return Polars.lit(self).ne_missing(other)
  end
  to_frame.select(Polars.col(name).ne_missing(other)).to_series
end

#new_from_index(index, length) ⇒ Series

Create a new Series filled with values from the given index.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4, 5])
s.new_from_index(1, 3)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         2
#         2
#         2
# ]

Returns:



4389
4390
4391
# File 'lib/polars/series.rb', line 4389

def new_from_index(index, length)
  Utils.wrap_s(_s.new_from_index(index, length))
end

#none?(&block) ⇒ Boolean Also known as: none

Check if all boolean values in the column are false.

Examples:

Polars::Series.new([true, false]).none?
# => false
Polars::Series.new([false, false]).none?
# => true
Polars::Series.new([nil, false]).none?
# => true

Returns:



612
613
614
615
616
617
618
# File 'lib/polars/series.rb', line 612

def none?(&block)
  if block_given?
    apply(&block).none?
  else
    to_frame.select(Polars.col(name).is_not.all).to_series[0]
  end
end

#null_countInteger

Count the null values in this Series.

Examples:

s = Polars::Series.new([1, nil, nil])
s.null_count
# => 2

Returns:

  • (Integer)


1990
1991
1992
# File 'lib/polars/series.rb', line 1990

def null_count
  _s.null_count
end

#pct_change(n: 1) ⇒ Series

Computes percentage change between values.

Percentage change (as fraction) between current element and most-recent non-null element at least n period(s) before the current element.

Computes the change from the previous row by default.

Examples:

Polars::Series.new(0..9).pct_change
# =>
# shape: (10,)
# Series: '' [f64]
# [
#         null
#         inf
#         1.0
#         0.5
#         0.333333
#         0.25
#         0.2
#         0.166667
#         0.142857
#         0.125
# ]
Polars::Series.new([1, 2, 4, 8, 16, 32, 64, 128, 256, 512]).pct_change(n: 2)
# =>
# shape: (10,)
# Series: '' [f64]
# [
#         null
#         null
#         3.0
#         3.0
#         3.0
#         3.0
#         3.0
#         3.0
#         3.0
#         3.0
# ]

Parameters:

  • n (Integer) (defaults to: 1)

    periods to shift for forming percent change.

Returns:



3992
3993
3994
# File 'lib/polars/series.rb', line 3992

def pct_change(n: 1)
  super
end

#peak_maxSeries

Get a boolean mask of the local maximum peaks.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4, 5])
s.peak_max
# =>
# shape: (5,)
# Series: 'a' [bool]
# [
#         false
#         false
#         false
#         false
#         true
# ]

Returns:



3688
3689
3690
# File 'lib/polars/series.rb', line 3688

def peak_max
  super
end

#peak_minSeries

Get a boolean mask of the local minimum peaks.

Examples:

s = Polars::Series.new("a", [4, 1, 3, 2, 5])
s.peak_min
# =>
# shape: (5,)
# Series: 'a' [bool]
# [
#         false
#         true
#         false
#         true
#         false
# ]

Returns:



3709
3710
3711
# File 'lib/polars/series.rb', line 3709

def peak_min
  super
end

#productNumeric

Reduce this Series to the product value.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.product
# => 6

Returns:

  • (Numeric)


874
875
876
# File 'lib/polars/series.rb', line 874

def product
  to_frame.select(Polars.col(name).product).to_series[0]
end

#qcut(quantiles, labels: nil, left_closed: false, allow_duplicates: false, include_breaks: false) ⇒ Series

Bin continuous values into discrete categories based on their quantiles.

Examples:

Divide a column into three categories according to pre-defined quantile probabilities.

s = Polars::Series.new("foo", [-2, -1, 0, 1, 2])
s.qcut([0.25, 0.75], labels: ["a", "b", "c"])
# =>
# shape: (5,)
# Series: 'foo' [cat]
# [
#         "a"
#         "a"
#         "b"
#         "b"
#         "c"
# ]

Divide a column into two categories using uniform quantile probabilities.

s.qcut(2, labels: ["low", "high"], left_closed: true)
# =>
# shape: (5,)
# Series: 'foo' [cat]
# [
#         "low"
#         "low"
#         "high"
#         "high"
#         "high"
# ]

Create a DataFrame with the breakpoint and category for each value.

cut = s.qcut([0.25, 0.75], include_breaks: true).alias("cut")
s.to_frame.with_columns(cut).unnest("cut")
# =>
# shape: (5, 3)
# ┌─────┬─────────────┬────────────┐
# │ foo ┆ break_point ┆ category   │
# │ --- ┆ ---         ┆ ---        │
# │ i64 ┆ f64         ┆ cat        │
# ╞═════╪═════════════╪════════════╡
# │ -2  ┆ -1.0        ┆ (-inf, -1] │
# │ -1  ┆ -1.0        ┆ (-inf, -1] │
# │ 0   ┆ 1.0         ┆ (-1, 1]    │
# │ 1   ┆ 1.0         ┆ (-1, 1]    │
# │ 2   ┆ inf         ┆ (1, inf]   │
# └─────┴─────────────┴────────────┘

Parameters:

  • quantiles (Array)

    Either a list of quantile probabilities between 0 and 1 or a positive integer determining the number of bins with uniform probability.

  • labels (Array) (defaults to: nil)

    Names of the categories. The number of labels must be equal to the number of cut points plus one.

  • left_closed (Boolean) (defaults to: false)

    Set the intervals to be left-closed instead of right-closed.

  • allow_duplicates (Boolean) (defaults to: false)

    If set to true, duplicates in the resulting quantiles are dropped, rather than raising a DuplicateError. This can happen even with unique probabilities, depending on the data.

  • include_breaks (Boolean) (defaults to: false)

    Include a column with the right endpoint of the bin each observation falls in. This will change the data type of the output from a Categorical to a Struct.

Returns:



1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/polars/series.rb', line 1158

def qcut(quantiles, labels: nil, left_closed: false, allow_duplicates: false, include_breaks: false)
  result = (
    to_frame
    .select(
      Polars.col(name).qcut(
        quantiles,
        labels: labels,
        left_closed: left_closed,
        allow_duplicates: allow_duplicates,
        include_breaks: include_breaks
      )
    )
    .to_series
  )

  if include_breaks
    result = result.struct.rename_fields(["break_point", "category"])
  end

  result
end

#quantile(quantile, interpolation: "nearest") ⇒ Float?

Get the quantile value of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.quantile(0.5)
# => 2.0

Parameters:

  • quantile (Float, nil)

    Quantile between 0.0 and 1.0.

  • interpolation ("nearest", "higher", "lower", "midpoint", "linear") (defaults to: "nearest")

    Interpolation method.

Returns:

  • (Float, nil)


1001
1002
1003
# File 'lib/polars/series.rb', line 1001

def quantile(quantile, interpolation: "nearest")
  _s.quantile(quantile, interpolation)
end

#rank(method: "average", reverse: false, seed: nil) ⇒ Series

Assign ranks to data, dealing with ties appropriately.

Examples:

The 'average' method:

s = Polars::Series.new("a", [3, 6, 1, 1, 6])
s.rank
# =>
# shape: (5,)
# Series: 'a' [f64]
# [
#         3.0
#         4.5
#         1.5
#         1.5
#         4.5
# ]

The 'ordinal' method:

s = Polars::Series.new("a", [3, 6, 1, 1, 6])
s.rank(method: "ordinal")
# =>
# shape: (5,)
# Series: 'a' [u32]
# [
#         3
#         4
#         1
#         2
#         5
# ]

Parameters:

  • method ("average", "min", "max", "dense", "ordinal", "random") (defaults to: "average")

    The method used to assign ranks to tied elements. The following methods are available (default is 'average'):

    • 'average' : The average of the ranks that would have been assigned to all the tied values is assigned to each value.
    • 'min' : The minimum of the ranks that would have been assigned to all the tied values is assigned to each value. (This is also referred to as "competition" ranking.)
    • 'max' : The maximum of the ranks that would have been assigned to all the tied values is assigned to each value.
    • 'dense' : Like 'min', but the rank of the next highest element is assigned the rank immediately after those assigned to the tied elements.
    • 'ordinal' : All values are given a distinct rank, corresponding to the order that the values occur in the Series.
    • 'random' : Like 'ordinal', but the rank for ties is not dependent on the order that the values occur in the Series.
  • reverse (Boolean) (defaults to: false)

    Reverse the operation.

  • seed (Integer) (defaults to: nil)

    If method: "random", use this as seed.

Returns:



3891
3892
3893
# File 'lib/polars/series.rb', line 3891

def rank(method: "average", reverse: false, seed: nil)
  super
end

#rechunk(in_place: false) ⇒ Series

Create a single chunk of memory for this Series.

Examples:

s1 = Polars::Series.new("a", [1, 2, 3])
s1.n_chunks
# => 1
s2 = Polars::Series.new("a", [4, 5, 6])
s = Polars.concat([s1, s2], rechunk: false)
s.n_chunks
# => 2
s.rechunk(in_place: true)
# =>
# shape: (6,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
#         4
#         5
#         6
# ]
s.n_chunks
# => 1

Parameters:

  • in_place (Boolean) (defaults to: false)

    In place or not.

Returns:



2450
2451
2452
2453
# File 'lib/polars/series.rb', line 2450

def rechunk(in_place: false)
  opt_s = _s.rechunk(in_place)
  in_place ? self : Utils.wrap_s(opt_s)
end

#reinterpret(signed: true) ⇒ Series

Reinterpret the underlying bits as a signed/unsigned integer.

This operation is only allowed for 64bit integers. For lower bits integers, you can safely use that cast operation.

Examples:

s = Polars::Series.new("a", [-(2**60), -2, 3])
s.reinterpret(signed: false)
# =>
# shape: (3,)
# Series: 'a' [u64]
# [
#         17293822569102704640
#         18446744073709551614
#         3
# ]

Parameters:

  • signed (Boolean) (defaults to: true)

    If true, reinterpret as :i64. Otherwise, reinterpret as :u64.

Returns:



3793
3794
3795
# File 'lib/polars/series.rb', line 3793

def reinterpret(signed: true)
  super
end

#rename(name, in_place: false) ⇒ Series

Rename this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.rename("b")

Parameters:

  • name (String)

    New name.

  • in_place (Boolean) (defaults to: false)

    Modify the Series in-place.

Returns:



1383
1384
1385
1386
1387
1388
1389
1390
# File 'lib/polars/series.rb', line 1383

def rename(name, in_place: false)
  if in_place
    _s.rename(name)
    self
  else
    self.alias(name)
  end
end

#replace(old, new = Expr::NO_DEFAULT, default: Expr::NO_DEFAULT, return_dtype: nil) ⇒ Series

Replace values by different values.

Examples:

Replace a single value by another value. Values that were not replaced remain unchanged.

s = Polars::Series.new([1, 2, 2, 3])
s.replace(2, 100)
# =>
# shape: (4,)
# Series: '' [i64]
# [
#         1
#         100
#         100
#         3
# ]

Replace multiple values by passing sequences to the old and new parameters.

s.replace([2, 3], [100, 200])
# =>
# shape: (4,)
# Series: '' [i64]
# [
#         1
#         100
#         100
#         200
# ]

Passing a mapping with replacements is also supported as syntactic sugar.

mapping = {2 => 100, 3 => 200}
s.replace(mapping)
# =>
# shape: (4,)
# Series: '' [i64]
# [
#         1
#         100
#         100
#         200
# ]

The original data type is preserved when replacing by values of a different data type.

s = Polars::Series.new(["x", "y", "z"])
mapping = {"x" => 1, "y" => 2, "z" => 3}
s.replace(mapping)
# =>
# shape: (3,)
# Series: '' [str]
# [
#         "1"
#         "2"
#         "3"
# ]

Parameters:

  • old (Object)

    Value or sequence of values to replace. Also accepts a mapping of values to their replacement.

  • new (Object) (defaults to: Expr::NO_DEFAULT)

    Value or sequence of values to replace by. Length must match the length of old or have length 1.

  • default (Object) (defaults to: Expr::NO_DEFAULT)

    Set values that were not replaced to this value. Defaults to keeping the original value. Accepts expression input. Non-expression inputs are parsed as literals.

  • return_dtype (Object) (defaults to: nil)

    The data type of the resulting Series. If set to nil (default), the data type is determined automatically based on the other inputs.

Returns:



4177
4178
4179
# File 'lib/polars/series.rb', line 4177

def replace(old, new = Expr::NO_DEFAULT, default: Expr::NO_DEFAULT, return_dtype: nil)
  super
end

#reshape(dims) ⇒ Series

Reshape this Series to a flat Series or a Series of Lists.

Examples:

s = Polars::Series.new("foo", [1, 2, 3, 4, 5, 6, 7, 8, 9])
square = s.reshape([3, 3])
# =>
# shape: (3,)
# Series: 'foo' [array[i64, 3]]
# [
#         [1, 2, 3]
#         [4, 5, 6]
#         [7, 8, 9]
# ]
square.reshape([9])
# =>
# shape: (9,)
# Series: 'foo' [i64]
# [
#         1
#         2
#         3
#         4
#         5
#         6
#         7
#         8
#         9
# ]

Parameters:

  • dims (Array)

    Tuple of the dimension sizes. If a -1 is used in any of the dimensions, that dimension is inferred.

Returns:



4217
4218
4219
# File 'lib/polars/series.rb', line 4217

def reshape(dims)
  super
end

#reverseSeries

Return Series in reverse order.

Examples:

s = Polars::Series.new("a", [1, 2, 3], dtype: :i8)
s.reverse
# =>
# shape: (3,)
# Series: 'a' [i8]
# [
#         3
#         2
#         1
# ]

Returns:



2470
2471
2472
# File 'lib/polars/series.rb', line 2470

def reverse
  super
end

#rleSeries

Get the lengths of runs of identical values.

Examples:

s = Polars::Series.new("s", [1, 1, 2, 1, nil, 1, 3, 3])
s.rle.struct.unnest
# =>
# shape: (6, 2)
# ┌─────┬───────┐
# │ len ┆ value │
# │ --- ┆ ---   │
# │ u32 ┆ i64   │
# ╞═════╪═══════╡
# │ 2   ┆ 1     │
# │ 1   ┆ 2     │
# │ 1   ┆ 1     │
# │ 1   ┆ null  │
# │ 1   ┆ 1     │
# │ 2   ┆ 3     │
# └─────┴───────┘

Returns:



1201
1202
1203
# File 'lib/polars/series.rb', line 1201

def rle
  super
end

#rle_idSeries

Map values to run IDs.

Similar to RLE, but it maps each value to an ID corresponding to the run into which it falls. This is especially useful when you want to define groups by runs of identical values rather than the values themselves.

Examples:

s = Polars::Series.new("s", [1, 1, 2, 1, nil, 1, 3, 3])
s.rle_id
# =>
# shape: (8,)
# Series: 's' [u32]
# [
#         0
#         0
#         1
#         2
#         3
#         4
#         5
#         5
# ]

Returns:



1229
1230
1231
# File 'lib/polars/series.rb', line 1229

def rle_id
  super
end

#rolling_max(window_size, weights: nil, min_periods: nil, center: false) ⇒ Series

Apply a rolling max (moving max) over the values in this array.

A window of length window_size will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the weight vector. The resulting values will be aggregated to their sum.

Examples:

s = Polars::Series.new("a", [100, 200, 300, 400, 500])
s.rolling_max(2)
# =>
# shape: (5,)
# Series: 'a' [i64]
# [
#         null
#         200
#         300
#         400
#         500
# ]

Parameters:

  • window_size (Integer)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3320
3321
3322
3323
3324
3325
3326
3327
# File 'lib/polars/series.rb', line 3320

def rolling_max(
  window_size,
  weights: nil,
  min_periods: nil,
  center: false
)
  super
end

#rolling_mean(window_size, weights: nil, min_periods: nil, center: false) ⇒ Series

Apply a rolling mean (moving mean) over the values in this array.

A window of length window_size will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the weight vector. The resulting values will be aggregated to their sum.

Examples:

s = Polars::Series.new("a", [100, 200, 300, 400, 500])
s.rolling_mean(2)
# =>
# shape: (5,)
# Series: 'a' [f64]
# [
#         null
#         150.0
#         250.0
#         350.0
#         450.0
# ]

Parameters:

  • window_size (Integer)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3361
3362
3363
3364
3365
3366
3367
3368
# File 'lib/polars/series.rb', line 3361

def rolling_mean(
  window_size,
  weights: nil,
  min_periods: nil,
  center: false
)
  super
end

#rolling_median(window_size, weights: nil, min_periods: nil, center: false) ⇒ Series

Compute a rolling median.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0])
s.rolling_median(3)
# =>
# shape: (6,)
# Series: 'a' [f64]
# [
#         null
#         null
#         2.0
#         3.0
#         4.0
#         6.0
# ]

Parameters:

  • window_size (Integer)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3529
3530
3531
3532
3533
3534
3535
3536
# File 'lib/polars/series.rb', line 3529

def rolling_median(
  window_size,
  weights: nil,
  min_periods: nil,
  center: false
)
  super
end

#rolling_min(window_size, weights: nil, min_periods: nil, center: false) ⇒ Series

Apply a rolling min (moving min) over the values in this array.

A window of length window_size will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the weight vector. The resulting values will be aggregated to their sum.

Examples:

s = Polars::Series.new("a", [100, 200, 300, 400, 500])
s.rolling_min(3)
# =>
# shape: (5,)
# Series: 'a' [i64]
# [
#         null
#         null
#         100
#         200
#         300
# ]

Parameters:

  • window_size (Integer)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3279
3280
3281
3282
3283
3284
3285
3286
# File 'lib/polars/series.rb', line 3279

def rolling_min(
  window_size,
  weights: nil,
  min_periods: nil,
  center: false
)
  super
end

#rolling_quantile(quantile, interpolation: "nearest", window_size: 2, weights: nil, min_periods: nil, center: false) ⇒ Series

Compute a rolling quantile.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0])
s.rolling_quantile(0.33, window_size: 3)
# =>
# shape: (6,)
# Series: 'a' [f64]
# [
#         null
#         null
#         1.0
#         2.0
#         3.0
#         4.0
# ]
s.rolling_quantile(0.33, interpolation: "linear", window_size: 3)
# =>
# shape: (6,)
# Series: 'a' [f64]
# [
#         null
#         null
#         1.66
#         2.66
#         3.66
#         5.32
# ]

Parameters:

  • quantile (Float)

    Quantile between 0.0 and 1.0.

  • interpolation ("nearest", "higher", "lower", "midpoint", "linear") (defaults to: "nearest")

    Interpolation method.

  • window_size (Integer) (defaults to: 2)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
# File 'lib/polars/series.rb', line 3585

def rolling_quantile(
  quantile,
  interpolation: "nearest",
  window_size: 2,
  weights: nil,
  min_periods: nil,
  center: false
)
  super
end

#rolling_skew(window_size, bias: true) ⇒ Series

Compute a rolling skew.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0])
s.rolling_skew(3)
# =>
# shape: (6,)
# Series: 'a' [f64]
# [
#         null
#         null
#         0.0
#         0.0
#         0.381802
#         0.0
# ]

Parameters:

  • window_size (Integer)

    Integer size of the rolling window.

  • bias (Boolean) (defaults to: true)

    If false, the calculations are corrected for statistical bias.

Returns:



3619
3620
3621
# File 'lib/polars/series.rb', line 3619

def rolling_skew(window_size, bias: true)
  super
end

#rolling_std(window_size, weights: nil, min_periods: nil, center: false, ddof: 1) ⇒ Series

Compute a rolling std dev.

A window of length window_size will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the weight vector. The resulting values will be aggregated to their sum.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0])
s.rolling_std(3)
# =>
# shape: (6,)
# Series: 'a' [f64]
# [
#         null
#         null
#         1.0
#         1.0
#         1.527525
#         2.0
# ]

Parameters:

  • window_size (Integer)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3444
3445
3446
3447
3448
3449
3450
3451
3452
# File 'lib/polars/series.rb', line 3444

def rolling_std(
  window_size,
  weights: nil,
  min_periods: nil,
  center: false,
  ddof: 1
)
  super
end

#rolling_sum(window_size, weights: nil, min_periods: nil, center: false) ⇒ Series

Apply a rolling sum (moving sum) over the values in this array.

A window of length window_size will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the weight vector. The resulting values will be aggregated to their sum.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4, 5])
s.rolling_sum(2)
# =>
# shape: (5,)
# Series: 'a' [i64]
# [
#         null
#         3
#         5
#         7
#         9
# ]

Parameters:

  • window_size (Integer)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3402
3403
3404
3405
3406
3407
3408
3409
# File 'lib/polars/series.rb', line 3402

def rolling_sum(
  window_size,
  weights: nil,
  min_periods: nil,
  center: false
)
  super
end

#rolling_var(window_size, weights: nil, min_periods: nil, center: false, ddof: 1) ⇒ Series

Compute a rolling variance.

A window of length window_size will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the weight vector. The resulting values will be aggregated to their sum.

Examples:

s = Polars::Series.new("a", [1.0, 2.0, 3.0, 4.0, 6.0, 8.0])
s.rolling_var(3)
# =>
# shape: (6,)
# Series: 'a' [f64]
# [
#         null
#         null
#         1.0
#         1.0
#         2.333333
#         4.0
# ]

Parameters:

  • window_size (Integer)

    The length of the window.

  • weights (Array) (defaults to: nil)

    An optional slice with the same length as the window that will be multiplied elementwise with the values in the window.

  • min_periods (Integer) (defaults to: nil)

    The number of values in the window that should be non-null before computing a result. If None, it will be set equal to window size.

  • center (Boolean) (defaults to: false)

    Set the labels at the center of the window

Returns:



3487
3488
3489
3490
3491
3492
3493
3494
3495
# File 'lib/polars/series.rb', line 3487

def rolling_var(
  window_size,
  weights: nil,
  min_periods: nil,
  center: false,
  ddof: 1
)
  super
end

#round(decimals = 0) ⇒ Series

Round underlying floating point data by decimals digits.

Examples:

s = Polars::Series.new("a", [1.12345, 2.56789, 3.901234])
s.round(2)
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         1.12
#         2.57
#         3.9
# ]

Parameters:

  • decimals (Integer) (defaults to: 0)

    number of decimals to round by.

Returns:



2814
2815
2816
# File 'lib/polars/series.rb', line 2814

def round(decimals = 0)
  super
end

#sample(n: nil, frac: nil, with_replacement: false, shuffle: false, seed: nil) ⇒ Series

Sample from this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4, 5])
s.sample(n: 2, seed: 0)
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         5
#         3
# ]

Parameters:

  • n (Integer) (defaults to: nil)

    Number of items to return. Cannot be used with frac. Defaults to 1 if frac is None.

  • frac (Float) (defaults to: nil)

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

  • with_replacement (Boolean) (defaults to: false)

    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 None (default), a random seed is used.

Returns:



3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
# File 'lib/polars/series.rb', line 3650

def sample(
  n: nil,
  frac: nil,
  with_replacement: false,
  shuffle: false,
  seed: nil
)
  if !n.nil? && !frac.nil?
    raise ArgumentError, "cannot specify both `n` and `frac`"
  end

  if n.nil? && !frac.nil?
    return Utils.wrap_s(_s.sample_frac(frac, with_replacement, shuffle, seed))
  end

  if n.nil?
    n = 1
  end
  Utils.wrap_s(_s.sample_n(n, with_replacement, shuffle, seed))
end

#scatter(idx, value) ⇒ Series Also known as: set_at_idx

Set values at the index locations.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.set_at_idx(1, 10)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         1
#         10
#         3
# ]

Parameters:

  • idx (Object)

    Integers representing the index locations.

  • value (Object)

    Replacement values.

Returns:



2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
# File 'lib/polars/series.rb', line 2635

def scatter(idx, value)
  if idx.is_a?(Integer)
    idx = [idx]
  end
  if idx.length == 0
    return self
  end

  idx = Series.new("", idx)
  if value.is_a?(Integer) || value.is_a?(Float) || Utils.bool?(value) || value.is_a?(::String) || value.nil?
    value = Series.new("", [value])

    # if we need to set more than a single value, we extend it
    if idx.length > 0
      value = value.extend_constant(value[0], idx.length - 1)
    end
  elsif !value.is_a?(Series)
    value = Series.new("", value)
  end
  _s.scatter(idx._s, value._s)
  self
end

#search_sorted(element, side: "any") ⇒ Integer

Find indices where elements should be inserted to maintain order.

Examples:

s = Polars::Series.new("set", [1, 2, 3, 4, 4, 5, 6, 7])
s.search_sorted(4)
# => 3
s.search_sorted(4, side: "left")
# => 3
s.search_sorted(4, side: "right")
# => 5
s.search_sorted([1, 4, 5])
# =>
# shape: (3,)
# Series: 'set' [u32]
# [
#         0
#         3
#         5
# ]
s.search_sorted([1, 4, 5], side: "left")
# =>
# shape: (3,)
# Series: 'set' [u32]
# [
#         0
#         3
#         5
# ]
s.search_sorted([1, 4, 5], side: "right")
# =>
# shape: (3,)
# Series: 'set' [u32]
# [
#         1
#         5
#         6
# ]

Parameters:

  • element (Object)

    Expression or scalar value.

Returns:

  • (Integer)


1930
1931
1932
1933
1934
1935
1936
# File 'lib/polars/series.rb', line 1930

def search_sorted(element, side: "any")
  if element.is_a?(Integer) || element.is_a?(Float)
    return Polars.select(Polars.lit(self).search_sorted(element, side: side)).item
  end
  element = Series.new(element)
  Polars.select(Polars.lit(self).search_sorted(element, side: side)).to_series
end

#set(filter, value) ⇒ Series

Note:

Use of this function is frequently an anti-pattern, as it can block optimization (predicate pushdown, etc). Consider using Polars.when(predicate).then(value).otherwise(self) instead.

Set masked values.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.set(s == 2, 10)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         1
#         10
#         3
# ]

Parameters:

  • filter (Series)

    Boolean mask.

  • value (Object)

    Value with which to replace the masked values.

Returns:



2611
2612
2613
# File 'lib/polars/series.rb', line 2611

def set(filter, value)
  Utils.wrap_s(_s.send("set_with_mask_#{DTYPE_TO_FFINAME.fetch(dtype.class)}", filter._s, value))
end

#set_sorted(reverse: false) ⇒ Series

Note:

This can lead to incorrect results if this Series is not sorted!! Use with care!

Flags the Series as sorted.

Enables downstream code to user fast paths for sorted arrays.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.set_sorted.max
# => 3

Parameters:

  • reverse (Boolean) (defaults to: false)

    If the Series order is reversed, e.g. descending.

Returns:



4370
4371
4372
# File 'lib/polars/series.rb', line 4370

def set_sorted(reverse: false)
  Utils.wrap_s(_s.set_sorted(reverse))
end

#shapeArray

Shape of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.shape
# => [3]

Returns:



139
140
141
# File 'lib/polars/series.rb', line 139

def shape
  [_s.len]
end

#shift(periods = 1) ⇒ Series

Shift the values by a given period.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.shift(1)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         null
#         1
#         2
# ]
s.shift(-1)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         2
#         3
#         null
# ]

Parameters:

  • periods (Integer) (defaults to: 1)

    Number of places to shift (may be negative).

Returns:



3187
3188
3189
# File 'lib/polars/series.rb', line 3187

def shift(periods = 1)
  super
end

#shift_and_fill(periods, fill_value) ⇒ Series

Shift the values by a given period and fill the resulting null values.

Parameters:

  • periods (Integer)

    Number of places to shift (may be negative).

  • fill_value (Object)

    Fill None values with the result of this expression.

Returns:



3199
3200
3201
# File 'lib/polars/series.rb', line 3199

def shift_and_fill(periods, fill_value)
  super
end

#shrink_dtypeSeries

Shrink numeric columns to the minimal required datatype.

Shrink to the dtype needed to fit the extrema of this Series. This can be used to reduce memory pressure.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4, 5, 6])
s.shrink_dtype
# =>
# shape: (6,)
# Series: 'a' [i8]
# [
#         1
#         2
#         3
#         4
#         5
#         6
# ]

Returns:



4414
4415
4416
# File 'lib/polars/series.rb', line 4414

def shrink_dtype
  super
end

#shrink_to_fit(in_place: false) ⇒ Series

Shrink Series memory usage.

Shrinks the underlying array capacity to exactly fit the actual data. (Note that this function does not change the Series data type).

Returns:



3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
# File 'lib/polars/series.rb', line 3731

def shrink_to_fit(in_place: false)
  if in_place
    _s.shrink_to_fit
    self
  else
    series = clone
    series._s.shrink_to_fit
    series
  end
end

#shuffle(seed: nil) ⇒ Series

Shuffle the contents of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.shuffle(seed: 1)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         2
#         1
#         3
# ]

Parameters:

  • seed (Integer, nil) (defaults to: nil)

    Seed for the random number generator.

Returns:



4239
4240
4241
# File 'lib/polars/series.rb', line 4239

def shuffle(seed: nil)
  super
end

#signSeries

Compute the element-wise indication of the sign.

Examples:

s = Polars::Series.new("a", [-9.0, -0.0, 0.0, 4.0, nil])
s.sign
# =>
# shape: (5,)
# Series: 'a' [f64]
# [
#         -1.0
#         -0.0
#         0.0
#         1.0
#         null
# ]

Returns:



2877
2878
2879
# File 'lib/polars/series.rb', line 2877

def sign
  super
end

#sinSeries

Compute the element-wise value for the sine.

Examples:

s = Polars::Series.new("a", [0.0, Math::PI / 2.0, Math::PI])
s.sin
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.0
#         1.0
#         1.2246e-16
# ]

Returns:



2896
2897
2898
# File 'lib/polars/series.rb', line 2896

def sin
  super
end

#sinhSeries

Compute the element-wise value for the hyperbolic sine.

Examples:

s = Polars::Series.new("a", [1.0, 0.0, -1.0])
s.sinh
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         1.175201
#         0.0
#         -1.175201
# ]

Returns:



3078
3079
3080
# File 'lib/polars/series.rb', line 3078

def sinh
  super
end

#skew(bias: true) ⇒ Float?

Compute the sample skewness of a data set.

For normally distributed data, the skewness should be about zero. For unimodal continuous distributions, a skewness value greater than zero means that there is more weight in the right tail of the distribution. The function skewtest can be used to determine if the skewness value is close enough to zero, statistically speaking.

Examples:

s = Polars::Series.new([1, 2, 2, 4, 5])
s.skew
# => 0.34776706224699483

Parameters:

  • bias (Boolean) (defaults to: true)

    If false, the calculations are corrected for statistical bias.

Returns:

  • (Float, nil)


4013
4014
4015
# File 'lib/polars/series.rb', line 4013

def skew(bias: true)
  _s.skew(bias)
end

#slice(offset, length = nil) ⇒ Series

Get a slice of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4])
s.slice(1, 2)
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         2
#         3
# ]

Parameters:

  • offset (Integer)

    Start index. Negative indexing is supported.

  • length (Integer, nil) (defaults to: nil)

    Length of the slice. If set to nil, all rows starting at the offset will be selected.

Returns:



1573
1574
1575
# File 'lib/polars/series.rb', line 1573

def slice(offset, length = nil)
  self.class._from_rbseries(_s.slice(offset, length))
end

#sort(reverse: false, nulls_last: false, multithreaded: true, in_place: false) ⇒ Series

Sort this Series.

Examples:

s = Polars::Series.new("a", [1, 3, 4, 2])
s.sort
# =>
# shape: (4,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
#         4
# ]
s.sort(reverse: true)
# =>
# shape: (4,)
# Series: 'a' [i64]
# [
#         4
#         3
#         2
#         1
# ]

Parameters:

  • reverse (Boolean) (defaults to: false)

    Reverse sort.

  • in_place (Boolean) (defaults to: false)

    Sort in place.

Returns:



1755
1756
1757
1758
1759
1760
1761
1762
# File 'lib/polars/series.rb', line 1755

def sort(reverse: false, nulls_last: false, multithreaded: true, in_place: false)
  if in_place
    self._s = _s.sort(reverse, nulls_last, multithreaded)
    self
  else
    Utils.wrap_s(_s.sort(reverse, nulls_last, multithreaded))
  end
end

#sqrtSeries

Compute the square root of the elements.

Examples:

s = Polars::Series.new([1, 2, 3])
s.sqrt
# =>
# shape: (3,)
# Series: '' [f64]
# [
#         1.0
#         1.414214
#         1.732051
# ]

Returns:



545
546
547
# File 'lib/polars/series.rb', line 545

def sqrt
  self**0.5
end

#std(ddof: 1) ⇒ Float?

Get the standard deviation of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.std
# => 1.0

Parameters:

  • ddof (Integer) (defaults to: 1)

    “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of elements.

Returns:

  • (Float, nil)


948
949
950
951
952
953
954
# File 'lib/polars/series.rb', line 948

def std(ddof: 1)
  if !is_numeric
    nil
  else
    to_frame.select(Polars.col(name).std(ddof: ddof)).to_series[0]
  end
end

#strStringNameSpace

Create an object namespace of all string related methods.

Returns:



4456
4457
4458
# File 'lib/polars/series.rb', line 4456

def str
  StringNameSpace.new(self)
end

#structStructNameSpace

Create an object namespace of all struct related methods.

Returns:



4463
4464
4465
# File 'lib/polars/series.rb', line 4463

def struct
  StructNameSpace.new(self)
end

#sumNumeric

Note:

Dtypes :i8, :u8, :i16, and :u16 are cast to :i64 before summing to prevent overflow issues.

Reduce this Series to the sum value.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.sum
# => 6

Returns:

  • (Numeric)


850
851
852
# File 'lib/polars/series.rb', line 850

def sum
  _s.sum
end

#tail(n = 10) ⇒ Series

Get the last n rows.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.tail(2)
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         2
#         3
# ]

Parameters:

  • n (Integer) (defaults to: 10)

    Number of rows to return.

Returns:



1702
1703
1704
# File 'lib/polars/series.rb', line 1702

def tail(n = 10)
  to_frame.select(F.col(name).tail(n)).to_series
end

#take(indices) ⇒ Series

Take values by index.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4])
s.take([1, 3])
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         2
#         4
# ]

Parameters:

  • indices (Array)

    Index location used for selection.

Returns:



1978
1979
1980
# File 'lib/polars/series.rb', line 1978

def take(indices)
  to_frame.select(Polars.col(name).take(indices)).to_series
end

#take_every(n) ⇒ Series

Take every nth value in the Series and return as new Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3, 4])
s.take_every(2)
# =>
# shape: (2,)
# Series: 'a' [i64]
# [
#         1
#         3
# ]

Returns:



1720
1721
1722
# File 'lib/polars/series.rb', line 1720

def take_every(n)
  super
end

#tanSeries

Compute the element-wise value for the tangent.

Examples:

s = Polars::Series.new("a", [0.0, Math::PI / 2.0, Math::PI])
s.tan
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.0
#         1.6331e16
#         -1.2246e-16
# ]

Returns:



2934
2935
2936
# File 'lib/polars/series.rb', line 2934

def tan
  super
end

#tanhSeries

Compute the element-wise value for the hyperbolic tangent.

Examples:

s = Polars::Series.new("a", [1.0, 0.0, -1.0])
s.tanh
# =>
# shape: (3,)
# Series: 'a' [f64]
# [
#         0.761594
#         0.0
#         -0.761594
# ]

Returns:



3116
3117
3118
# File 'lib/polars/series.rb', line 3116

def tanh
  super
end

#to_aArray

Convert this Series to a Ruby Array. This operation clones data.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.to_a
# => [1, 2, 3]

Returns:



2411
2412
2413
# File 'lib/polars/series.rb', line 2411

def to_a
  _s.to_a
end

#to_dummies(separator: "_", drop_first: false) ⇒ DataFrame

Get dummy variables.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.to_dummies
# =>
# shape: (3, 3)
# ┌─────┬─────┬─────┐
# │ a_1 ┆ a_2 ┆ a_3 │
# │ --- ┆ --- ┆ --- │
# │ u8  ┆ u8  ┆ u8  │
# ╞═════╪═════╪═════╡
# │ 1   ┆ 0   ┆ 0   │
# │ 0   ┆ 1   ┆ 0   │
# │ 0   ┆ 0   ┆ 1   │
# └─────┴─────┴─────┘

Returns:



1023
1024
1025
# File 'lib/polars/series.rb', line 1023

def to_dummies(separator: "_", drop_first: false)
  Utils.wrap_df(_s.to_dummies(separator, drop_first))
end

#to_frame(name = nil) ⇒ DataFrame

Cast this Series to a DataFrame.

Examples:

s = Polars::Series.new("a", [123, 456])
s.to_frame
# =>
# shape: (2, 1)
# ┌─────┐
# │ a   │
# │ --- │
# │ i64 │
# ╞═════╡
# │ 123 │
# │ 456 │
# └─────┘
s.to_frame("xyz")
# =>
# shape: (2, 1)
# ┌─────┐
# │ xyz │
# │ --- │
# │ i64 │
# ╞═════╡
# │ 123 │
# │ 456 │
# └─────┘

Returns:



749
750
751
752
753
754
# File 'lib/polars/series.rb', line 749

def to_frame(name = nil)
  if name
    return Utils.wrap_df(RbDataFrame.new([rename(name)._s]))
  end
  Utils.wrap_df(RbDataFrame.new([_s]))
end

#to_numoNumo::NArray

Convert this Series to a Numo array. This operation clones data but is completely safe.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.to_numo
# =>
# Numo::Int64#shape=[3]
# [1, 2, 3]

Returns:

  • (Numo::NArray)


2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
# File 'lib/polars/series.rb', line 2556

def to_numo
  if !has_validity
    if is_datelike
      Numo::RObject.cast(to_a)
    elsif is_numeric
      # TODO make more efficient
      {
        UInt8 => Numo::UInt8,
        UInt16 => Numo::UInt16,
        UInt32 => Numo::UInt32,
        UInt64 => Numo::UInt64,
        Int8 => Numo::Int8,
        Int16 => Numo::Int16,
        Int32 => Numo::Int32,
        Int64 => Numo::Int64,
        Float32 => Numo::SFloat,
        Float64 => Numo::DFloat
      }.fetch(dtype.class).cast(to_a)
    elsif is_boolean
      Numo::Bit.cast(to_a)
    else
      _s.to_numo
    end
  elsif is_datelike
    Numo::RObject.cast(to_a)
  else
    _s.to_numo
  end
end

#to_physicalSeries

Cast to physical representation of the logical dtype.

  • :date -> :i32
  • :datetime -> :i64
  • :time -> :i64
  • :duration -> :i64
  • :cat -> :u32
  • other data types will be left unchanged.

Examples:

s = Polars::Series.new("values", ["a", nil, "x", "a"])
s.cast(:cat).to_physical
# =>
# shape: (4,)
# Series: 'values' [u32]
# [
#         0
#         null
#         1
#         0
# ]

Returns:



2399
2400
2401
# File 'lib/polars/series.rb', line 2399

def to_physical
  super
end

#to_sString Also known as: inspect

Returns a string representing the Series.

Returns:



146
147
148
# File 'lib/polars/series.rb', line 146

def to_s
  _s.to_s
end

#top_k(k: 5) ⇒ Boolean

Return the k largest elements.

Examples:

s = Polars::Series.new("a", [2, 5, 1, 4, 3])
s.top_k(k: 3)
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         5
#         4
#         3
# ]

Parameters:

  • k (Integer) (defaults to: 5)

    Number of elements to return.

Returns:



1782
1783
1784
# File 'lib/polars/series.rb', line 1782

def top_k(k: 5)
  super
end

#unique(maintain_order: false) ⇒ Series Also known as: uniq

Get unique elements in series.

Examples:

s = Polars::Series.new("a", [1, 2, 2, 3])
s.unique.sort
# =>
# shape: (3,)
# Series: 'a' [i64]
# [
#         1
#         2
#         3
# ]

Parameters:

  • maintain_order (Boolean) (defaults to: false)

    Maintain order of data. This requires more work.

Returns:



1956
1957
1958
# File 'lib/polars/series.rb', line 1956

def unique(maintain_order: false)
  super
end

#unique_countsSeries

Return a count of the unique values in the order of appearance.

Examples:

s = Polars::Series.new("id", ["a", "b", "b", "c", "c", "c"])
s.unique_counts
# =>
# shape: (3,)
# Series: 'id' [u32]
# [
#         1
#         2
#         3
# ]

Returns:



1289
1290
1291
# File 'lib/polars/series.rb', line 1289

def unique_counts
  super
end

#value_counts(sort: false, parallel: false, name: nil, normalize: false) ⇒ DataFrame

Count the unique values in a Series.

Examples:

s = Polars::Series.new("a", [1, 2, 2, 3])
s.value_counts.sort("a")
# =>
# shape: (3, 2)
# ┌─────┬────────┐
# │ a   ┆ counts │
# │ --- ┆ ---    │
# │ i64 ┆ u32    │
# ╞═════╪════════╡
# │ 1   ┆ 1      │
# │ 2   ┆ 2      │
# │ 3   ┆ 1      │
# └─────┴────────┘

Parameters:

  • sort (Boolean) (defaults to: false)

    Ensure the output is sorted from most values to least.

Returns:



1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
# File 'lib/polars/series.rb', line 1254

def value_counts(
  sort: false,
  parallel: false,
  name: nil,
  normalize: false
)
  if name.nil?
    if normalize
      name = "proportion"
    else
      name = "count"
    end
  end
  DataFrame._from_rbdf(
    self._s.value_counts(
      sort, parallel, name, normalize
    )
  )
end

#var(ddof: 1) ⇒ Float?

Get variance of this Series.

Examples:

s = Polars::Series.new("a", [1, 2, 3])
s.var
# => 1.0

Parameters:

  • ddof (Integer) (defaults to: 1)

    “Delta Degrees of Freedom”: the divisor used in the calculation is N - ddof, where N represents the number of elements.

Returns:

  • (Float, nil)


968
969
970
971
972
973
974
# File 'lib/polars/series.rb', line 968

def var(ddof: 1)
  if !is_numeric
    nil
  else
    to_frame.select(Polars.col(name).var(ddof: ddof)).to_series[0]
  end
end

#zip_with(mask, other) ⇒ Series

Take values from self or other based on the given mask.

Where mask evaluates true, take values from self. Where mask evaluates false, take values from other.

Examples:

s1 = Polars::Series.new([1, 2, 3, 4, 5])
s2 = Polars::Series.new([5, 4, 3, 2, 1])
s1.zip_with(s1 < s2, s2)
# =>
# shape: (5,)
# Series: '' [i64]
# [
#         1
#         2
#         3
#         2
#         1
# ]
mask = Polars::Series.new([true, false, true, false, true])
s1.zip_with(mask, s2)
# =>
# shape: (5,)
# Series: '' [i64]
# [
#         1
#         4
#         3
#         2
#         5
# ]

Parameters:

  • mask (Series)

    Boolean Series.

  • other (Series)

    Series of same type.

Returns:



3243
3244
3245
# File 'lib/polars/series.rb', line 3243

def zip_with(mask, other)
  Utils.wrap_s(_s.zip_with(mask._s, other._s))
end

#|(other) ⇒ Series

Bitwise OR.

Returns:



164
165
166
167
168
169
# File 'lib/polars/series.rb', line 164

def |(other)
  if !other.is_a?(Series)
    other = Series.new([other])
  end
  Utils.wrap_s(_s.bitor(other._s))
end