Class: Rover::DataFrame

Inherits:
Object
  • Object
show all
Defined in:
lib/rover/data_frame.rb

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ DataFrame

Returns a new instance of DataFrame.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
# File 'lib/rover/data_frame.rb', line 3

def initialize(*args)
  data, options = process_args(args)

  @vectors = {}
  types = options[:types] || {}

  if data.is_a?(DataFrame)
    data.vectors.each do |k, v|
      @vectors[k] = v
    end
  elsif data.is_a?(Hash)
    data.to_h.each do |k, v|
      @vectors[k] =
        if v.respond_to?(:to_a)
          Vector.new(v, type: types[k])
        else
          v
        end
    end

    # handle scalars
    size = @vectors.values.find { |v| v.is_a?(Vector) }&.size || 1
    @vectors.each_key do |k|
      @vectors[k] = to_vector(@vectors[k], size: size, type: types[k])
    end
  elsif data.is_a?(Array)
    vectors = {}
    raise ArgumentError, "Array elements must be hashes" unless data.all? { |d| d.is_a?(Hash) }
    keys = data.flat_map(&:keys).uniq
    keys.each do |k|
      vectors[k] = []
    end
    data.each do |d|
      keys.each do |k|
        vectors[k] << d[k]
      end
    end
    vectors.each do |k, v|
      @vectors[k] = to_vector(v, type: types[k])
    end
  elsif defined?(ActiveRecord) && (data.is_a?(ActiveRecord::Relation) || (data.is_a?(Class) && data < ActiveRecord::Base) || data.is_a?(ActiveRecord::Result))
    result = data.is_a?(ActiveRecord::Result) ? data : data.connection_pool.with_connection { |c| c.select_all(data.all.to_sql) }
    result.columns.each_with_index do |k, i|
      @vectors[k] = to_vector(result.rows.map { |r| r[i] }, type: types[k])
    end
  else
    raise ArgumentError, "Cannot cast to data frame: #{data.class.name}"
  end

  # check keys
  @vectors.each_key do |k|
    check_key(k)
  end

  # check sizes
  sizes = @vectors.values.map(&:size).uniq
  if sizes.size > 1
    raise ArgumentError, "Different sizes: #{sizes}"
  end
end

Instance Method Details

#+(other) ⇒ Object



368
369
370
# File 'lib/rover/data_frame.rb', line 368

def +(other)
  dup.concat(other)
end

#==(other) ⇒ Object

don’t check types



409
410
411
412
413
# File 'lib/rover/data_frame.rb', line 409

def ==(other)
  size == other.size &&
  keys == other.keys &&
  keys.all? { |k| self[k].to_numo == other[k].to_numo }
end

#[](where) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/rover/data_frame.rb', line 64

def [](where)
  if (where.is_a?(Vector) && where.to_numo.is_a?(Numo::Bit)) || where.is_a?(Numeric) || where.is_a?(Range) || (where.is_a?(Array) && where.all? { |v| v.is_a?(Integer) })
    new_vectors = {}
    @vectors.each do |k, v|
      new_vectors[k] = v[where]
    end
    DataFrame.new(new_vectors)
  elsif where.is_a?(Array)
    # multiple columns
    df = DataFrame.new
    where.each do |k|
      check_column(k)
      df[k] = @vectors[k]
    end
    df
  else
    # single column
    @vectors[where]
  end
end

#[]=(k, v) ⇒ Object

Raises:

  • (ArgumentError)


102
103
104
105
106
107
# File 'lib/rover/data_frame.rb', line 102

def []=(k, v)
  check_key(k)
  v = to_vector(v, size: size)
  raise ArgumentError, "Size mismatch (given #{v.size}, expected #{size})" if @vectors.any? && v.size != size
  @vectors[k] = v
end

#any?Boolean

should this check for columns as well?

Returns:

  • (Boolean)


116
117
118
# File 'lib/rover/data_frame.rb', line 116

def any?
  size > 0
end

#clearObject



125
126
127
# File 'lib/rover/data_frame.rb', line 125

def clear
  @vectors.clear
end

#concat(other) ⇒ Object

in-place, like Array#concat TODO make more performant

Raises:

  • (ArgumentError)


374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/rover/data_frame.rb', line 374

def concat(other)
  raise ArgumentError, "Must be a data frame" unless other.is_a?(DataFrame)

  size = self.size
  vectors.each do |k, v|
    @vectors[k] = Vector.new(v.to_a + (other[k] ? other[k].to_a : [nil] * other.size))
  end
  (other.vector_names - vector_names).each do |k|
    @vectors[k] = Vector.new([nil] * size + other[k].to_a)
  end
  self
end

#deep_dupObject



360
361
362
363
364
365
366
# File 'lib/rover/data_frame.rb', line 360

def deep_dup
  df = DataFrame.new
  @vectors.each do |k, v|
    df[k] = v.dup
  end
  df
end

#delete(key) ⇒ Object



150
151
152
# File 'lib/rover/data_frame.rb', line 150

def delete(key)
  @vectors.delete(key)
end

#each_rowObject



85
86
87
88
89
90
91
# File 'lib/rover/data_frame.rb', line 85

def each_row
  return enum_for(:each_row) unless block_given?

  size.times do |i|
    yield @vectors.map { |k, v| [k, v[i]] }.to_h
  end
end

#empty?Boolean

should this check for columns as well?

Returns:

  • (Boolean)


121
122
123
# File 'lib/rover/data_frame.rb', line 121

def empty?
  size == 0
end

#except(*keys) ⇒ Object



154
155
156
# File 'lib/rover/data_frame.rb', line 154

def except(*keys)
  dup.except!(*keys)
end

#except!(*keys) ⇒ Object



158
159
160
161
162
163
# File 'lib/rover/data_frame.rb', line 158

def except!(*keys)
  keys.each do |key|
    delete(key)
  end
  self
end

#first(n = 1) ⇒ Object



177
178
179
180
181
182
183
# File 'lib/rover/data_frame.rb', line 177

def first(n = 1)
  new_vectors = {}
  @vectors.each do |k, v|
    new_vectors[k] = v.first(n)
  end
  DataFrame.new(new_vectors)
end

#group(*columns) ⇒ Object



349
350
351
# File 'lib/rover/data_frame.rb', line 349

def group(*columns)
  Group.new(self, columns.flatten)
end

#head(n = 5) ⇒ Object



169
170
171
# File 'lib/rover/data_frame.rb', line 169

def head(n = 5)
  first(n)
end

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


165
166
167
# File 'lib/rover/data_frame.rb', line 165

def include?(key)
  @vectors.include?(key)
end

#inner_join(other, on: nil) ⇒ Object

see join for options



399
400
401
# File 'lib/rover/data_frame.rb', line 399

def inner_join(other, on: nil)
  join(other, on: on, how: "inner")
end

#inspectObject Also known as: to_s

TODO handle long text better



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/rover/data_frame.rb', line 299

def inspect
  return "#<Rover::DataFrame>" if keys.empty?

  lines = []
  line_start = 0
  spaces = 2

  summarize = size >= 30

  @vectors.each do |k, v|
    v = summarize ? v.first(5).to_a + ["..."] + v.last(5).to_a : v.to_a
    width = ([k] + v).map(&:to_s).map(&:size).max
    width = 3 if width < 3

    if lines.empty? || lines[-2].map { |l| l.size + spaces }.sum + width > 120
      line_start = lines.size
      lines << []
      v.size.times do |i|
        lines << []
      end
      lines << []
    end

    lines[line_start] << "%#{width}s" % k.to_s
    v.each_with_index do |v2, i|
      lines[line_start + 1 + i] << "%#{width}s" % v2.to_s
    end
  end

  lines.pop
  lines.map { |l| l.join(" " * spaces) }.join("\n")
end

#keysObject Also known as: names, vector_names



133
134
135
# File 'lib/rover/data_frame.rb', line 133

def keys
  @vectors.keys
end

#last(n = 1) ⇒ Object



185
186
187
188
189
190
191
# File 'lib/rover/data_frame.rb', line 185

def last(n = 1)
  new_vectors = {}
  @vectors.each do |k, v|
    new_vectors[k] = v.last(n)
  end
  DataFrame.new(new_vectors)
end

#left_join(other, on: nil) ⇒ Object

see join for options



404
405
406
# File 'lib/rover/data_frame.rb', line 404

def left_join(other, on: nil)
  join(other, on: on, how: "left")
end

#merge(other) ⇒ Object



387
388
389
# File 'lib/rover/data_frame.rb', line 387

def merge(other)
  dup.merge!(other)
end

#merge!(other) ⇒ Object



391
392
393
394
395
396
# File 'lib/rover/data_frame.rb', line 391

def merge!(other)
  other.vectors.each do |k, v|
    self[k] = v
  end
  self
end

#one_hot(drop: false) ⇒ Object

TODO raise error when collision



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/rover/data_frame.rb', line 220

def one_hot(drop: false)
  df = DataFrame.new
  vectors.each do |k, v|
    if v.to_numo.is_a?(Numo::RObject)
      df.merge!(v.one_hot(drop: drop, prefix: "#{k}_"))
    else
      df[k] = v
    end
  end
  df
rescue ArgumentError => e
  if e.message == "All elements must be strings"
    # better error message
    raise ArgumentError, "All elements must be numeric or strings"
  end
  raise e
end

#plot(x = nil, y = nil, type: nil, group: nil, stacked: nil) ⇒ Object

Raises:

  • (ArgumentError)


415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
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
463
464
465
466
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/rover/data_frame.rb', line 415

def plot(x = nil, y = nil, type: nil, group: nil, stacked: nil)
  require "vega"

  raise ArgumentError, "Must specify columns" if keys.size != 2 && (!x || !y)
  x ||= keys[0]
  y ||= keys[1]
  type ||= begin
    if self[x].numeric? && self[y].numeric?
      "scatter"
    elsif types[x] == :object && self[y].numeric?
      "column"
    else
      raise "Cannot determine type. Use the type option."
    end
  end
  data = self[group.nil? ? [x, y] : [x, y, group]]

  case type
  when "line", "area"
    x_type =
      if data[x].numeric?
        "quantitative"
      elsif data[x].all? { |v| v.is_a?(Date) || v.is_a?(Time) }
        "temporal"
      else
        "nominal"
      end

    scale = x_type == "temporal" ? {type: "utc"} : {}
    encoding = {
      x: {field: x, type: x_type, scale: scale},
      y: {field: y, type: "quantitative"}
    }
    encoding[:color] = {field: group} if group

    Vega.lite
      .data(data)
      .mark(type: type, tooltip: true, interpolate: "cardinal", point: {size: 60})
      .encoding(encoding)
      .config(axis: {labelFontSize: 12})
  when "pie"
    raise ArgumentError, "Cannot use group option with pie chart" unless group.nil?

    Vega.lite
      .data(data)
      .mark(type: "arc", tooltip: true)
      .encoding(
        color: {field: x, type: "nominal", sort: "none", axis: {title: nil}, legend: {labelFontSize: 12}},
        theta: {field: y, type: "quantitative"}
      )
      .view(stroke: nil)
  when "column"
    encoding = {
      x: {field: x, type: "nominal", sort: "none", axis: {labelAngle: 0}},
      y: {field: y, type: "quantitative"}
    }
    if group
      encoding[:color] = {field: group}
      encoding[:xOffset] = {field: group} unless stacked
    end

    Vega.lite
      .data(data)
      .mark(type: "bar", tooltip: true)
      .encoding(encoding)
      .config(axis: {labelFontSize: 12})
  when "bar"
    encoding = {
      # TODO determine label angle
      y: {field: x, type: "nominal", sort: "none", axis: {labelAngle: 0}},
      x: {field: y, type: "quantitative"}
    }
    if group
      encoding[:color] = {field: group}
      encoding[:yOffset] = {field: group} unless stacked
    end

    Vega.lite
      .data(data)
      .mark(type: "bar", tooltip: true)
      .encoding(encoding)
      .config(axis: {labelFontSize: 12})
  when "scatter"
    encoding = {
      x: {field: x, type: "quantitative", scale: {zero: false}},
      y: {field: y, type: "quantitative", scale: {zero: false}},
      size: {value: 60}
    }
    encoding[:color] = {field: group} if group

    Vega.lite
      .data(data)
      .mark(type: "circle", tooltip: true)
      .encoding(encoding)
      .config(axis: {labelFontSize: 12})
  else
    raise ArgumentError, "Invalid type: #{type}"
  end
end

#rename(mapping) ⇒ Object



139
140
141
142
143
144
145
146
147
148
# File 'lib/rover/data_frame.rb', line 139

def rename(mapping)
  mapping.each_key do |k|
    check_column(k)
  end
  # use transform_keys! to preserve order
  @vectors.transform_keys! do |k|
    mapping[k] || k
  end
  self
end

#sample(*args, **kwargs) ⇒ Object



193
194
195
196
197
# File 'lib/rover/data_frame.rb', line 193

def sample(*args, **kwargs)
  # TODO make more efficient
  indexes = (0...size).to_a.sample(*args, **kwargs)
  self[indexes]
end

#shapeObject



129
130
131
# File 'lib/rover/data_frame.rb', line 129

def shape
  [size, @vectors.size]
end

#sizeObject Also known as: length, count



109
110
111
# File 'lib/rover/data_frame.rb', line 109

def size
  @vectors.values.first&.size || 0
end

#sort_by(&block) ⇒ Object



345
346
347
# File 'lib/rover/data_frame.rb', line 345

def sort_by(&block)
  dup.sort_by!(&block)
end

#sort_by!Object



333
334
335
336
337
338
339
340
341
342
343
# File 'lib/rover/data_frame.rb', line 333

def sort_by!
  indexes =
    size.times.sort_by do |i|
      yield @vectors.map { |k, v| [k, v[i]] }.to_h
    end

  @vectors.each do |k, v|
    self[k] = v.to_numo.at(indexes)
  end
  self
end

#tail(n = 5) ⇒ Object



173
174
175
# File 'lib/rover/data_frame.rb', line 173

def tail(n = 5)
  last(n)
end

#to_aObject



199
200
201
202
203
204
205
# File 'lib/rover/data_frame.rb', line 199

def to_a
  a = []
  each_row do |row|
    a << row
  end
  a
end

#to_csvObject



238
239
240
241
242
243
244
245
246
247
# File 'lib/rover/data_frame.rb', line 238

def to_csv
  require "csv"
  CSV.generate do |csv|
    csv << keys
    numo = vectors.values.map(&:to_numo)
    size.times do |i|
      csv << numo.map { |n| n[i] }
    end
  end
end

#to_hObject



207
208
209
210
211
212
213
# File 'lib/rover/data_frame.rb', line 207

def to_h
  hsh = {}
  @vectors.each do |k, v|
    hsh[k] = v.to_a
  end
  hsh
end

#to_htmlObject

for IRuby



288
289
290
291
292
293
294
295
296
# File 'lib/rover/data_frame.rb', line 288

def to_html
  require "iruby"
  if size > 7
    # pass 8 rows so maxrows is applied
    IRuby::HTML.table((self[0..4] + self[-4..-1]).to_h, maxrows: 7)
  else
    IRuby::HTML.table(to_h)
  end
end

#to_numoObject



215
216
217
# File 'lib/rover/data_frame.rb', line 215

def to_numo
  Numo::NArray.column_stack(vectors.values.map(&:to_numo))
end

#to_parquetObject



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/rover/data_frame.rb', line 249

def to_parquet
  require "parquet"

  schema = {}
  types.each do |name, type|
    schema[name] =
      case type
      when :int64
        :int64
      when :uint64
        :uint64
      when :float64
        :double
      when :float32
        :float
      when :bool
        :boolean
      when :object
        if @vectors[name].all? { |v| v.is_a?(String) }
          :string
        else
          raise "Unknown type"
        end
      else
        type
      end
  end
  # TODO improve performance
  raw_records = []
  size.times do |i|
    raw_records << @vectors.map { |_, v| v[i] }
  end
  table = Arrow::Table.new(schema, raw_records)
  buffer = Arrow::ResizableBuffer.new(1024)
  table.save(buffer, format: :parquet)
  buffer.data.to_s
end

#typesObject



98
99
100
# File 'lib/rover/data_frame.rb', line 98

def types
  @vectors.map { |k, v| [k, v.type] }.to_h
end

#vectorsObject

dup to prevent direct modification of keys



94
95
96
# File 'lib/rover/data_frame.rb', line 94

def vectors
  @vectors.dup
end