carray 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +343 -0
  3. data/README.md +25 -4
  4. data/carray.gemspec +3 -2
  5. data/ext/ca_axis_dispatch.c +6 -0
  6. data/ext/ca_axis_group.c +7 -7
  7. data/ext/ca_binop_dispatch.c +8 -0
  8. data/ext/ca_binop_dispatch.h +1 -0
  9. data/ext/ca_categorical_iterator.c +14 -14
  10. data/ext/ca_kernel_iterator.c +116 -231
  11. data/ext/ca_kernel_iterator.h +416 -258
  12. data/ext/ca_obj_array.c +4 -4
  13. data/ext/ca_obj_bincmp.c +28 -4
  14. data/ext/ca_obj_binop.c +46 -12
  15. data/ext/ca_obj_bitarray.c +2 -4
  16. data/ext/ca_obj_bitfield.c +88 -4
  17. data/ext/ca_obj_byte_swap.c +4 -4
  18. data/ext/ca_obj_const_string.c +422 -257
  19. data/ext/ca_obj_face.c +73 -33
  20. data/ext/ca_obj_fake.c +114 -13
  21. data/ext/ca_obj_farray.c +7 -1
  22. data/ext/ca_obj_fixlen_string.c +51 -17
  23. data/ext/ca_obj_grid.c +179 -19
  24. data/ext/ca_obj_meld.c +74 -118
  25. data/ext/ca_obj_moncmp.c +9 -1
  26. data/ext/ca_obj_monop.c +100 -36
  27. data/ext/ca_obj_object.c +63 -29
  28. data/ext/ca_obj_reduce.c +17 -5
  29. data/ext/ca_obj_refer.c +162 -23
  30. data/ext/ca_obj_remap.c +69 -10
  31. data/ext/ca_obj_repeat.c +1 -1
  32. data/ext/ca_obj_roll.c +3 -4
  33. data/ext/ca_obj_select.c +12 -7
  34. data/ext/ca_obj_select_axis.c +9 -6
  35. data/ext/ca_obj_shift.c +1 -0
  36. data/ext/ca_obj_stack.c +315 -116
  37. data/ext/ca_obj_stride.c +177 -53
  38. data/ext/ca_obj_string.c +20 -4
  39. data/ext/ca_obj_tile.c +3 -4
  40. data/ext/ca_obj_triop.c +24 -13
  41. data/ext/ca_obj_window.c +23 -15
  42. data/ext/ca_op_ipower.c +71 -23
  43. data/ext/ca_op_powi.h +6 -29
  44. data/ext/ca_sort_kernels.h +3 -0
  45. data/ext/ca_sweep_engine.c +90 -23
  46. data/ext/ca_sweep_engine.h +5 -6
  47. data/ext/caframe_csv_reader.c +2 -2
  48. data/ext/carray.h +5 -2
  49. data/ext/carray_access.c +125 -103
  50. data/ext/carray_address_basis.c +209 -1
  51. data/ext/carray_attribute.c +8 -0
  52. data/ext/carray_broadcast.c +5 -6
  53. data/ext/carray_build_flags.h +1 -1
  54. data/ext/carray_call_cfunc.c +5 -8
  55. data/ext/carray_cast.c +319 -48
  56. data/ext/carray_cast_func.rb +37 -5
  57. data/ext/carray_conversion.c +65 -7
  58. data/ext/carray_copy.c +24 -0
  59. data/ext/carray_core.c +874 -72
  60. data/ext/carray_count.c +28 -9
  61. data/ext/carray_element.c +22 -12
  62. data/ext/carray_factorize.c +11 -11
  63. data/ext/carray_histogram.c +27 -5
  64. data/ext/carray_index_classifier.c +7 -5
  65. data/ext/carray_internal.h +241 -12
  66. data/ext/carray_kernels_bincmp.c +2007 -3
  67. data/ext/carray_kernels_binop.c +25502 -5336
  68. data/ext/carray_kernels_init.c +22 -22
  69. data/ext/carray_kernels_monop.c +10739 -3771
  70. data/ext/carray_kernels_reduce_aggregate.c +4429 -702
  71. data/ext/carray_kernels_reduce_boolean.c +1533 -15
  72. data/ext/carray_kernels_reduce_cumulative.c +1808 -248
  73. data/ext/carray_kernels_reduce_extreme.c +4508 -511
  74. data/ext/carray_kernels_reduce_variance.c +2284 -152
  75. data/ext/carray_kernels_scan.c +240 -240
  76. data/ext/carray_kernels_search.c +4211 -264
  77. data/ext/carray_kernels_sort.c +367 -450
  78. data/ext/carray_lazy.c +63 -1
  79. data/ext/carray_loop.c +10 -3
  80. data/ext/carray_mask.c +247 -149
  81. data/ext/carray_median_percentile.c +17 -12
  82. data/ext/carray_memory_view.c +54 -29
  83. data/ext/carray_operator.c +219 -55
  84. data/ext/carray_order.c +55 -11
  85. data/ext/carray_partition.c +1 -1
  86. data/ext/carray_random.c +5 -2
  87. data/ext/carray_round.c +24 -1
  88. data/ext/carray_scatter.c +4 -0
  89. data/ext/carray_segment.c +1 -1
  90. data/ext/carray_slab.c +110 -25
  91. data/ext/carray_sort.c +7 -4
  92. data/ext/carray_sort_kernel.c +24 -0
  93. data/ext/carray_struct.c +21 -6
  94. data/ext/carray_test.c +154 -53
  95. data/ext/carray_time_text.c +8 -2
  96. data/ext/carray_utils.c +124 -54
  97. data/ext/extconf.rb +11 -0
  98. data/ext/mk_call_cfunc.rb +6 -11
  99. data/ext/mkkernel.rb +383 -121
  100. data/ext/ruby_carray.c +4 -1
  101. data/ext/version.h +4 -4
  102. data/lib/carray/attribute.rb +25 -1
  103. data/lib/carray/autoload_carray.rb +3 -3
  104. data/lib/carray/autoload_method_extension.rb +5 -3
  105. data/lib/carray/axis_group.rb +22 -13
  106. data/lib/carray/basics.rb +27 -9
  107. data/lib/carray/bincount_nd.rb +8 -2
  108. data/lib/carray/block_iterator.rb +65 -24
  109. data/lib/carray/categorical.rb +27 -16
  110. data/lib/carray/categorical_iterator.rb +4 -3
  111. data/lib/carray/complex.rb +2 -2
  112. data/lib/carray/conditional.rb +55 -6
  113. data/lib/carray/const_string.rb +74 -0
  114. data/lib/carray/construct.rb +2 -2
  115. data/lib/carray/core_extensions.rb +19 -68
  116. data/lib/carray/data_type_extension.rb +1 -0
  117. data/lib/carray/fixlen_string.rb +83 -1
  118. data/lib/carray/frame/column_verbs.rb +102 -16
  119. data/lib/carray/frame/concat.rb +50 -6
  120. data/lib/carray/frame/convert.rb +19 -0
  121. data/lib/carray/frame/csv_parser.rb +45 -36
  122. data/lib/carray/frame/describe.rb +4 -2
  123. data/lib/carray/frame/frame.rb +436 -83
  124. data/lib/carray/frame/group.rb +731 -78
  125. data/lib/carray/frame/io.rb +216 -73
  126. data/lib/carray/frame/join.rb +166 -43
  127. data/lib/carray/frame/records.rb +9 -7
  128. data/lib/carray/frame/reshape.rb +109 -11
  129. data/lib/carray/frame/sort.rb +57 -9
  130. data/lib/carray/frame/verbs.rb +448 -60
  131. data/lib/carray/frame/windows.rb +71 -9
  132. data/lib/carray/fuse_source.rb +4 -2
  133. data/lib/carray/inspect.rb +7 -2
  134. data/lib/carray/iterator.rb +40 -0
  135. data/lib/carray/key_windows.rb +10 -4
  136. data/lib/carray/lazy.rb +28 -24
  137. data/lib/carray/mask_gap_fill.rb +37 -17
  138. data/lib/carray/meld_reduce.rb +1 -1
  139. data/lib/carray/methods/bin.rb +3 -0
  140. data/lib/carray/methods/choose.rb +3 -2
  141. data/lib/carray/methods/composition.rb +1 -1
  142. data/lib/carray/methods/factorize.rb +2 -0
  143. data/lib/carray/methods/gather_nd.rb +4 -1
  144. data/lib/carray/methods/is_in.rb +23 -3
  145. data/lib/carray/methods/locate_addr.rb +63 -12
  146. data/lib/carray/methods/meshgrid.rb +3 -1
  147. data/lib/carray/methods/repeat.rb +11 -1
  148. data/lib/carray/record_order.rb +35 -6
  149. data/lib/carray/runtime.rb +57 -8
  150. data/lib/carray/segment_iterator.rb +42 -24
  151. data/lib/carray/serialize.rb +56 -17
  152. data/lib/carray/slab_iterator.rb +1 -1
  153. data/lib/carray/stack.rb +21 -9
  154. data/lib/carray/string.rb +6 -6
  155. data/lib/carray/string_operation_extension.rb +25 -4
  156. data/lib/carray/struct_builder.rb +4 -1
  157. data/lib/carray/time.rb +195 -46
  158. data/lib/carray/window_iterator.rb +64 -16
  159. data/yard-stubs/ca_obj_array.rb +26 -1
  160. data/yard-stubs/ca_obj_bitfield.rb +4 -1
  161. data/yard-stubs/ca_obj_refer.rb +3 -0
  162. data/yard-stubs/ca_obj_window.rb +2 -1
  163. data/yard-stubs/carray_access.rb +4 -2
  164. data/yard-stubs/carray_cast.rb +14 -5
  165. data/yard-stubs/carray_conversion.rb +8 -2
  166. data/yard-stubs/carray_count.rb +6 -3
  167. data/yard-stubs/carray_mask.rb +20 -1
  168. data/yard-stubs/carray_math.rb +36 -16
  169. data/yard-stubs/carray_memory_view.rb +7 -0
  170. data/yard-stubs/carray_order.rb +6 -0
  171. data/yard-stubs/carray_scatter.rb +2 -1
  172. data/yard-stubs/carray_test.rb +23 -7
  173. metadata +17 -3
@@ -6,7 +6,57 @@
6
6
  # -> group_by_category, so the frame layer only builds the key and hands
7
7
  # the group iterator back (exposure, §4.3).
8
8
 
9
+ require "carray/distance_limit"
10
+
9
11
  class CAFrame
12
+ # How many rows hold each value of a column, or each combination of the
13
+ # values of several (every column by default), as a frame: the values as
14
+ # its index (one column) or its first columns (several), and their counts
15
+ # in a column +name:+ ("count"). +sort:+ orders the rows by +:count+, the
16
+ # most first (the default; ties in the order the values first appear), by
17
+ # +:value+, or not at all (+false+, the order the values first appear). A
18
+ # row with a masked value is not counted, as +group_by+ leaves it out.
19
+ #
20
+ # df.value_counts("station")
21
+ # df.value_counts("station", "weather", sort: :value)
22
+ #
23
+ # The columns are given as +select+ takes them. +group_by(...).size+ is the
24
+ # same count in the order of the groups.
25
+ #
26
+ # @return [CAFrame]
27
+ # @raise [ArgumentError] for another +sort:+, or a +name:+ a key has.
28
+ def value_counts (*names, sort: :count, name: "count")
29
+ unless [:count, :value, false].include?(sort)
30
+ raise ArgumentError, "value_counts: sort: is :count, :value or false (got #{sort.inspect})"
31
+ end
32
+ keys = names.empty? ? column_names : names_selected(names, "value_counts")
33
+ if keys.empty?
34
+ hint = @index ? "; name the index (#{@axis_name.inspect}) to count its values" : ""
35
+ raise ArgumentError, "value_counts: the frame has no columns#{hint}"
36
+ end
37
+ name = column_name_arg(name, "value_counts")
38
+ if keys.include?(name)
39
+ raise ArgumentError,
40
+ "value_counts: a counted column is named #{name.inspect}; name the count " \
41
+ "otherwise, as in value_counts(..., name: \"n\")"
42
+ end
43
+ out = group_by(*keys).size(name: name)
44
+ case sort
45
+ when :count then out.sort_by_key(name, descending: true)
46
+ when :value
47
+ # A categorical key is ordered by its labels, as CArray#value_counts
48
+ # orders one; its codes are in the order labels were met.
49
+ cols = keys.map do |key|
50
+ col = out.__send__(:key_column, key, "value_counts")
51
+ col.is_a?(CACategorical) ? col.to_type(:object) : col
52
+ end
53
+ out.__send__(:select_rows, CArray.sort_addr(*cols))
54
+ else out
55
+ end
56
+ rescue ArgumentError, KeyError, TypeError, CArray::DataTypeError => e
57
+ raise e.class, e.message.sub(/\A(group_by|size|sort_by_key):/, "value_counts:"), e.backtrace
58
+ end
59
+
10
60
  # Group rows by one or more keys. Each key is a column name (String) or an
11
61
  # external length-N CArray. Returns a GroupedFrame.
12
62
  #
@@ -98,7 +148,7 @@ class CAFrame
98
148
  # as an empty reduction does: UNDEF for +mean+, 0 for +count+ and +sum+.
99
149
  # A row whose time is masked belongs to no bin.
100
150
  #
101
- # +by:+ (a column name or an Array of them) bins each group of rows on its
151
+ # +by:+ (a column name, a CArray key or an Array of them) bins each group of rows on its
102
152
  # own: a group is the rows sharing the +by:+ values and a bin. The result
103
153
  # then has no index: the +by:+ columns and the bin times (named +name+)
104
154
  # are its first columns, the groups in the order their +by:+ values first
@@ -113,7 +163,9 @@ class CAFrame
113
163
  # @param origin [nil, Time, String, CATime::Element] where bins start.
114
164
  # @param label [:left, :right] which end of a bin names it and is closed.
115
165
  # @param fill [Boolean] whether bins with no rows are rows of the result.
116
- # @param by [nil, String, Array<String>] columns whose groups are binned apart.
166
+ # @param by [nil, String, CArray, Array<String, CArray>] columns whose groups
167
+ # are binned apart; a CArray key (one value per row, as group_by takes it)
168
+ # is labelled "key0", "key1", ... by its place.
117
169
  # @return [GroupedFrame]
118
170
  # @raise [ArgumentError] when the column is not a CATime, or +label:+ is
119
171
  # neither :left nor :right, or +by:+ names the time column.
@@ -141,13 +193,18 @@ class CAFrame
141
193
  # resample with by:. A group is a (by values, bin) pair, coded as
142
194
  # group * bins + bin, so the codes run through the groups in the order their
143
195
  # by values first appear and through each group's bins in time order.
196
+ # A by: key is a column name or, as group_by takes it, a CArray of one
197
+ # value per row; a CArray key is labelled "key0", "key1", ... by its place.
144
198
  private def resample_by(name, time, bins, grid, by, fill)
145
- by_names = column_keys(Array(by), "resample")
146
- raise ArgumentError, "resample: by: names no column" if by_names.empty?
147
- if by_names.include?(name)
199
+ keys = by.is_a?(Array) ? by : [by]
200
+ raise ArgumentError, "resample: by: names no column" if keys.empty?
201
+ keys.each { |k| column_key(k, "resample") unless k.is_a?(CArray) }
202
+ if keys.include?(name)
148
203
  raise ArgumentError, "resample: by: names the time column #{name.inspect}"
149
204
  end
150
- by_cols = by_names.map { |n| key_column(n, "resample") }
205
+ by_names = keys.each_with_index.map { |k, i| k.is_a?(String) ? k : "key#{i}" }
206
+ CAFrame.__send__(:refuse_repeated_names, by_names + [name], "resample")
207
+ by_cols = keys.map { |k| key_column(k, "resample") }
151
208
  gcat = CACategorical.send(:from_keys, by_cols)
152
209
  ng = gcat.labels.size
153
210
  nb = grid.elements
@@ -173,7 +230,7 @@ class CAFrame
173
230
  parts + [blabels[b]]
174
231
  end
175
232
  cat = CACategorical.from_codes(codes, labels)
176
- key_names = by_names + (@columns.key?(name) ? [name] : [])
233
+ key_names = keys.grep(String) + (@columns.key?(name) ? [name] : [])
177
234
  GroupedFrame.new(self, cat, "group", key_names, label_columns: columns)
178
235
  end
179
236
 
@@ -183,9 +240,19 @@ class CAFrame
183
240
  # or one-year grid and then given the bins' unit, as the labels without
184
241
  # fill: are.
185
242
  private def resample_grid(bins, unit)
186
- base = CATime::Resolution.parse(unit).base
187
- if %i[Y M].include?(base)
188
- CArray.time_range(bins.min, bins.max, unit: base, step: unit).to_unit(bins.unit)
243
+ res = CATime::Resolution.parse(unit)
244
+ if %i[Y M].include?(res.base)
245
+ months = res.base == :Y ? res.count * 12 : res.count
246
+ grid = CArray.time_range(bins.min, bins.max, unit: :M, step: "#{months} months")
247
+ # A key coarser than the bins holds one bin for several grid points.
248
+ # key-labels: the bins of a grid, labelled by the caller
249
+ grid.to_unit(bins.unit).unique(sort: true)
250
+ elsif CATimeUnitAlgebra.ratio(res, bins.unit).denominator != 1
251
+ # A step finer than the key is stepped in its own unit; the key holds
252
+ # one bin for several of its points.
253
+ grid = CArray.time_range(bins.min, bins.max, unit: res.base, step: unit)
254
+ # key-labels: the bins of a grid, labelled by the caller
255
+ grid.to_unit(bins.unit).unique(sort: true)
189
256
  else
190
257
  CArray.time_range(bins.min, bins.max, unit: bins.unit, step: unit)
191
258
  end
@@ -234,6 +301,348 @@ class CAFrame
234
301
  end
235
302
  col
236
303
  end
304
+
305
+ # Each column reduced over all the rows, as a frame of one row: the
306
+ # reductions of +GroupedFrame+ with every row in one group. Given names, the
307
+ # frame of those columns; without, of every column whose type has the
308
+ # reduction. A column keeps its type where the reduction keeps it (the
309
+ # earliest time of a time column is a time), and +min_count:+ /
310
+ # +fill_value:+ / +keep_rows:+ work as they do for a group. A frame with no
311
+ # rows still gives its one row: a sum of nothing is 0, a mean UNDEF.
312
+ #
313
+ # df.mean # => one row, the mean of every numeric column
314
+ # df.max("tmax", "tmin") # => one row, the two maxima
315
+ # df["tmax"] - df.mean("tmax", keep_rows: true) # the anomaly on each row
316
+ #
317
+ # For one column's value as a Ruby value, reduce the column: +df["tmax"].mean+.
318
+ #
319
+ # @!method sum(*names, min_count: nil, fill_value: nil, keep_rows: false)
320
+ # @return [CAFrame] one row.
321
+ # @!method mean(*names, min_count: nil, fill_value: nil, keep_rows: false)
322
+ # @return [CAFrame] one row.
323
+ # @!method min(*names, min_count: nil, fill_value: nil, keep_rows: false)
324
+ # @return [CAFrame] one row.
325
+ # @!method max(*names, min_count: nil, fill_value: nil, keep_rows: false)
326
+ # @return [CAFrame] one row.
327
+ # @!method prod(*names, min_count: nil, fill_value: nil, keep_rows: false)
328
+ # @return [CAFrame] one row.
329
+ # @!method accumulate(*names, min_count: nil, fill_value: nil, keep_rows: false)
330
+ # @return [CAFrame] one row.
331
+ # @!method median(*names, min_count: nil, fill_value: nil, keep_rows: false)
332
+ # @return [CAFrame] one row.
333
+ # @!method variance(*names, min_count: nil, fill_value: nil, keep_rows: false)
334
+ # @return [CAFrame] one row.
335
+ # @!method stddev(*names, min_count: nil, fill_value: nil, keep_rows: false)
336
+ # @return [CAFrame] one row.
337
+ # @!method variancep(*names, min_count: nil, fill_value: nil, keep_rows: false)
338
+ # @return [CAFrame] one row.
339
+ # @!method stddevp(*names, min_count: nil, fill_value: nil, keep_rows: false)
340
+ # @return [CAFrame] one row.
341
+ # @!method first(*names, keep_rows: false)
342
+ # @return [CAFrame] one row: each column's first present value.
343
+ # @!method last(*names, keep_rows: false)
344
+ # @return [CAFrame] one row: each column's last present value.
345
+ # @!method nunique(*names, keep_rows: false)
346
+ # @return [CAFrame] one row: each column's number of distinct present values.
347
+ # @!method count(*names, keep_rows: false)
348
+ # @return [CAFrame] one row: each column's number of present values.
349
+ # @!method all(*names, keep_rows: false)
350
+ # @return [CAFrame] one row, for the boolean columns.
351
+ # @!method any(*names, keep_rows: false)
352
+ # @return [CAFrame] one row, for the boolean columns.
353
+ CArray.send(:define_named_methods, self,
354
+ [:sum, :mean, :min, :max, :prod, :accumulate, :median,
355
+ :variance, :stddev, :variancep, :stddevp], :reduce_all_rows)
356
+
357
+ CArray.send(:define_named_methods, self,
358
+ [:first, :last, :nunique, :count, :all, :any], :reduce_all_rows_to_a_value)
359
+
360
+ # Each column's +p+-th percentile (0 to 100) over all the rows, as a frame
361
+ # of one row, as {#median} gives the 50th. The percentage comes first, then
362
+ # the names.
363
+ #
364
+ # df.percentile(90, "revenue")
365
+ #
366
+ # @param p [Numeric] the percentage.
367
+ # @param names [Array<String>] the columns; default every column that has
368
+ # a percentile.
369
+ # @return [CAFrame, CArray] one row; with +keep_rows: true+ the frame's
370
+ # rows, one name giving the CArray.
371
+ def percentile (p, *names, min_count: nil, fill_value: nil, keep_rows: false)
372
+ CAFrame.__send__(:check_percentage, p)
373
+ reduce_all_rows(:percentile, *names, min_count: min_count, fill_value: fill_value,
374
+ keep_rows: keep_rows, args: [p])
375
+ end
376
+
377
+ # Each column's five quartile percentiles over all the rows, as
378
+ # +CArray#quantile+ gives them, as a frame of one row: a column "x" gives
379
+ # the five columns "x_p0", "x_p25", "x_p50", "x_p75" and "x_p100". With
380
+ # +keep_rows: true+ every row holds them.
381
+ #
382
+ # df.quantile("temp")
383
+ #
384
+ # @param names [Array<String>] the columns; default every column that has
385
+ # a quantile.
386
+ # @return [CAFrame]
387
+ def quantile (*names, keep_rows: false)
388
+ named = {}
389
+ ColumnWalk.new(self).over(:quantile, names) do |col, name|
390
+ named[name] = col.quantile(axis: 0, keep_axis: true).map do |q|
391
+ keep_rows ? q[CArray.int64(@nrow).fill(0), *([nil] * (q.ndim - 1))].copy : q
392
+ end
393
+ end
394
+ cols = CAFrame.__send__(:quantile_columns, named)
395
+ return CAFrame.new(cols) unless keep_rows
396
+ return CAFrame.new(cols, axis_name: @axis_name, index: @index&.copy)
397
+ end
398
+
399
+ # The five columns a quantile gives a column, by name.
400
+ def self.quantile_columns(named)
401
+ named.each_with_object({}) do |(name, quartiles), cols|
402
+ QUANTILE_SUFFIXES.zip(quartiles) { |suffix, q| cols["#{name}_#{suffix}"] = q }
403
+ end
404
+ end
405
+ private_class_method :quantile_columns
406
+
407
+ QUANTILE_SUFFIXES = %w[p0 p25 p50 p75 p100].freeze
408
+ private_constant :QUANTILE_SUFFIXES
409
+
410
+ private def reduce_all_rows (reduction, *names, min_count: nil, fill_value: nil, keep_rows: false, args: [])
411
+ walk = ColumnWalk.new(self)
412
+ walk.__send__(:refuse_unknown_fill_columns, reduction, fill_value)
413
+ walk.__send__(:refuse_wrong_reduction_arguments, reduction, args,
414
+ { min_count: min_count }.compact)
415
+ return reduce_down_the_rows(reduction, names, keep_rows, args) do |name|
416
+ fill = fill_value.is_a?(Hash) ? fill_value[name] : fill_value
417
+ { min_count: min_count, fill_value: fill }.compact
418
+ end
419
+ end
420
+
421
+ private def reduce_all_rows_to_a_value (reduction, *names, keep_rows: false)
422
+ return reduce_down_the_rows(reduction, names, keep_rows) { |_| {} }
423
+ end
424
+
425
+ # Each named column, or every column whose type has the reduction,
426
+ # reduced by the column itself along the rows to one row (keep_axis), so
427
+ # it keeps its type as the column's reduction keeps it. The block gives a
428
+ # column's keywords. A frame of one row with no index; with +keep_rows+,
429
+ # each row holding the result, as a group's +keep_rows+ gives it.
430
+ private def reduce_down_the_rows (reduction, names, keep_rows, args = [])
431
+ meth = reduction == :count ? :count_not_masked : reduction
432
+ named = {}
433
+ out = ColumnWalk.new(self).over(reduction, names, [], args) do |col, name|
434
+ result = col.public_send(meth, *args, axis: 0, keep_axis: true, **yield(name))
435
+ if keep_rows
436
+ result = result[CArray.int64(@nrow).fill(0), *([nil] * (result.ndim - 1))].copy
437
+ end
438
+ named[name] = result
439
+ end
440
+ return CAFrame.new(named) unless keep_rows
441
+ return out if out.is_a?(CArray)
442
+ return CAFrame.new(named, axis_name: @axis_name, index: @index&.copy)
443
+ end
444
+
445
+ # Values computed down the rows, one per row, as +GroupedFrame+ computes
446
+ # them within each group, with every row in one group: each row's rank
447
+ # (+order+, int64, 0 the smallest) and the running values up to and
448
+ # including it. Given names, one name gives the CArray and several a frame
449
+ # of those columns; without names, a frame of every column whose type has
450
+ # the operation. A frame is on the frame's rows and index.
451
+ #
452
+ # df["total"] = df.cumsum("rain")
453
+ # df["rank"] = df.order("temp", descending: true)
454
+ #
455
+ # @!method order(*names, descending: false, method: :ordinal, kind: :quick)
456
+ # @return [CAFrame, CArray]
457
+ # @!method cumsum(*names)
458
+ # @return [CAFrame, CArray]
459
+ # @!method cumprod(*names)
460
+ # @return [CAFrame, CArray]
461
+ # @!method cummax(*names)
462
+ # @return [CAFrame, CArray]
463
+ # @!method cummin(*names)
464
+ # @return [CAFrame, CArray]
465
+ # @!method cumcount(*names)
466
+ # @return [CAFrame, CArray]
467
+ CArray.send(:define_named_methods, self,
468
+ [:order, :cumsum, :cumprod, :cummax, :cummin, :cumcount], :run_down_all_rows)
469
+
470
+ private def run_down_all_rows (operation, *names, **keywords)
471
+ # The keywords are the core's to check, before any column is read.
472
+ CArray.float64(1).public_send(operation, **keywords)
473
+ out = ColumnWalk.new(self).over(operation, names, [], [], keywords) do |col, _|
474
+ col.public_send(operation, **(col.ndim > 1 ? keywords.merge(axis: 0) : keywords))
475
+ end
476
+ ColumnWalk.new(self).__send__(:refuse_no_column_on_rows, operation, out, @nrow)
477
+ return out if out.is_a?(CArray)
478
+ return CAFrame.new(out, axis_name: @axis_name, index: @index&.copy)
479
+ end
480
+
481
+ # The frame's own walk over its columns: the one rule of a frame-wide verb
482
+ # (ColumnVerbs) -- which columns, and the shape of the answer -- for the
483
+ # verbs that run down all the rows, each column computed by itself.
484
+ class ColumnWalk
485
+ include CAFrame::ColumnVerbs
486
+
487
+ def initialize (frame)
488
+ @frame = frame
489
+ end
490
+
491
+ def over (verb, names, key_names = [], args = [], keywords = {}, &block)
492
+ return over_named_columns(verb, names, key_names, args, keywords, &block)
493
+ end
494
+ end
495
+ private_constant :ColumnWalk
496
+
497
+ # The values of the columns moved along the rows: +n:+ rows back (a
498
+ # negative +n+ looks ahead), or the value at an exact distance of the key
499
+ # -- +before: "1 hour"+ gives each row the value of the row whose key is
500
+ # one hour earlier, +after:+ one hour later. The key is the index, or the
501
+ # column +on:+ names; it is a time, a duration or a number, and the
502
+ # distance is a duration such as "1 hour" (or a CATimedelta value) or a
503
+ # number accordingly. A row with no row at that key gets UNDEF; so does a
504
+ # row whose key is masked. The rows need not be in order. The result is
505
+ # new arrays in every form, so writing to it, or filling it once it is
506
+ # stored as a column, does not reach the column it came from.
507
+ #
508
+ # df["dtemp"] = df["temp"] - df.lag("temp", before: "1 hour")
509
+ # df.lag("temp", n: 1) # the previous row
510
+ #
511
+ # +GroupedFrame#lag+ does the same within each group. Given names, one
512
+ # name gives the CArray and several a frame of those columns; without
513
+ # names, a frame of every column (the +on:+ column left out). A frame is
514
+ # on the frame's rows and index. A result shows the column's attributes, as +CArray#lag+'s
515
+ # does.
516
+ #
517
+ # @param names [Array<String>] the columns.
518
+ # @param n [Integer] rows back.
519
+ # @param before [String, CATimedelta::Element, Numeric] the distance back.
520
+ # @param after [String, CATimedelta::Element, Numeric] the distance ahead.
521
+ # @param on [String] the key column, with +before:+ or +after:+ (default the
522
+ # index).
523
+ # @return [CArray, CAFrame]
524
+ # @raise [ArgumentError] when +n:+, +before:+ and +after:+ are combined,
525
+ # when +on:+ comes without a distance, when there is no key, or when the
526
+ # key repeats (the row at a key would not be one row).
527
+ def lag (*names, n: nil, before: nil, after: nil, on: nil)
528
+ distance = lag_distance("lag", n, before, after, on)
529
+ walk = ColumnWalk.new(self)
530
+ if distance.nil?
531
+ step = n.nil? ? 1 : n
532
+ # A wrong n: would otherwise read as no column having a lag.
533
+ CArray.float64(1).lag(step)
534
+ cols = walk.over(:lag, names, [], [step]) do |col, _|
535
+ (col.ndim > 1 ? col.lag(step, axis: 0) : col.lag(step)).copy
536
+ end
537
+ else
538
+ addr = lag_addresses("lag", [CArray.int64(nrow).seq], *distance)
539
+ cols = walk.over(:lag, names, [distance.first], [1]) do |col, _|
540
+ col[addr, *([nil] * (col.ndim - 1))].copy
541
+ end
542
+ end
543
+ return cols if cols.is_a?(CArray)
544
+ CAFrame.new(cols, axis_name: @axis_name, index: @index&.copy)
545
+ end
546
+
547
+ # [key name, key, sign, width] for a lag by distance; nil for one by rows.
548
+ private def lag_distance (verb, n, before, after, on)
549
+ if before.nil? && after.nil?
550
+ raise ArgumentError, "#{verb}: on: goes with before: or after:" unless on.nil?
551
+ return nil
552
+ end
553
+ unless n.nil?
554
+ raise ArgumentError, "#{verb}: give n: (rows) or before: / after: (a distance of the key), not both"
555
+ end
556
+ unless before.nil? || after.nil?
557
+ raise ArgumentError, "#{verb}: give before: or after:, not both"
558
+ end
559
+ if on.nil?
560
+ unless @index
561
+ raise ArgumentError, "#{verb}: the frame has no index; name the key column with on:"
562
+ end
563
+ on_name = @axis_name
564
+ else
565
+ on_name = column_key(on, verb)
566
+ end
567
+ key = key_column(on_name, verb)
568
+ unless key.is_a?(CATime) || key.is_a?(CATimedelta) || (!key.face? && key.numeric? && !key.complex?)
569
+ raise ArgumentError,
570
+ "#{verb}: the key #{on_name.inspect} is #{CArray::Inspector.type_label(key)}; " \
571
+ "a distance is taken along a time, a duration or a number"
572
+ end
573
+ label = before.nil? ? "#{verb}: after:" : "#{verb}: before:"
574
+ width = CArray::DistanceLimit.read(before || after, key, label)
575
+ return [on_name, key, before.nil? ? :+ : :-, width]
576
+ end
577
+
578
+ # For each row, the address of the row of its row set whose key is its own
579
+ # key moved by the width; masked where there is none. A row in no set is
580
+ # masked too, and so is a row whose key is NaN or infinite, which is no
581
+ # distance from any key (as in windows).
582
+ private def lag_addresses (verb, row_sets, _on_name, key, sign, width)
583
+ key = key.mask_invalid if key.float?
584
+ addr = CArray.int64(nrow)
585
+ addr[] = UNDEF
586
+ row_sets.each do |rows|
587
+ keys = key[rows]
588
+ next if keys.count_not_masked == 0
589
+ if keys.nunique < keys.count_not_masked
590
+ raise ArgumentError,
591
+ "#{verb}: the key repeats#{row_sets.size > 1 ? " within a group" : ""}, " \
592
+ "so the row at a key is not one row"
593
+ end
594
+ addr[rows] = rows[lag_target(keys, sign, width).locate_addr(keys)]
595
+ end
596
+ return addr
597
+ end
598
+
599
+ # The keys moved by the width. A time is moved on the finer of its unit and
600
+ # the width's, so that an hour back from a day is not rounded onto the day.
601
+ private def lag_target (keys, sign, width)
602
+ if width.is_a?(CATimedelta::Element) &&
603
+ CATimeUnitAlgebra.same_group?(keys.unit.base, width.unit.base)
604
+ keys = keys.to_unit(CATimeUnitAlgebra.finer(keys.unit, width.unit))
605
+ end
606
+ return lag_integer_target(keys, sign, width) if keys.integer?
607
+ return keys.public_send(sign, width)
608
+ end
609
+
610
+ LAG_UNSIGNED = [CA_UINT8, CA_UINT16, CA_UINT32, CA_UINT64].freeze
611
+ private_constant :LAG_UNSIGNED
612
+
613
+ # Integer keys moved by the width exactly, in int64 (or as Ruby integers
614
+ # for a 64-bit key a step does not fit in). A target outside the key's
615
+ # range is masked, so it matches no row rather than wrapping onto one; a
616
+ # width that is not a whole number matches no row either.
617
+ private def lag_integer_target (keys, sign, width)
618
+ bits = keys.bytes * 8
619
+ if LAG_UNSIGNED.include?(keys.data_type)
620
+ lo, hi = 0, 2**bits - 1
621
+ else
622
+ lo, hi = -2**(bits - 1), 2**(bits - 1) - 1
623
+ end
624
+ step = width.is_a?(Integer) ? width : nil
625
+ if step.nil? && width.respond_to?(:finite?) && width.finite? && width == width.floor
626
+ step = width.to_i
627
+ end
628
+ if step.nil? || step > hi - lo
629
+ out = CArray.int64(*keys.shape)
630
+ out[] = UNDEF
631
+ return out
632
+ end
633
+ if bits < 64
634
+ return keys.to_type(CA_INT64).public_send(sign, step)
635
+ end
636
+ if step > 2**63 - 1
637
+ moved = keys.to_type(CA_OBJECT).public_send(sign, step)
638
+ moved[moved.lt(lo).or(moved.gt(hi))] = UNDEF
639
+ return moved
640
+ end
641
+ out = keys.copy
642
+ out[sign == :- ? keys.lt(lo + step) : keys.gt(hi - step)] = UNDEF
643
+ return out.public_send(sign, step)
644
+ end
645
+
237
646
  end
238
647
 
239
648
  # GroupedFrame — the result of +CAFrame#group_by+ (memo §11.6, §16).
@@ -281,6 +690,40 @@ class GroupedFrame
281
690
  @labels.size
282
691
  end
283
692
 
693
+ # The number of rows in each group, as a frame of one column, "size"
694
+ # unless +name:+ says otherwise, labelled as a reduction's result is. A row
695
+ # whose key is masked is in no group, so the sizes need not add up to the
696
+ # frame's nrow.
697
+ #
698
+ # @param name [String] the result column's name.
699
+ # @return [CAFrame]
700
+ # @raise [ArgumentError] when a key has that name.
701
+ def size (name: "size")
702
+ refuse_changed_rows("size")
703
+ name = @frame.__send__(:column_name_arg, name, "size")
704
+ if @key_names.include?(name) || @axis_name == name
705
+ raise ArgumentError,
706
+ "size: a key is named #{name.inspect}; name the result otherwise, as in size(name: \"n\")"
707
+ end
708
+ return result_frame({ name => @cat.category_sizes.int64 }, false)
709
+ end
710
+
711
+ # Each group's label (an Array of the key values for several keys) and its
712
+ # rows as a sub-frame sharing the frame's columns, in the order of
713
+ # +labels+. Without a block, an Enumerator.
714
+ #
715
+ # df.group_by("station").each { |station, rows| puts station, rows.nrow }
716
+ #
717
+ # @yieldparam label [Object, Array] the group's key value(s).
718
+ # @yieldparam rows [CAFrame] the group's rows.
719
+ # @return [GroupedFrame] self
720
+ def each
721
+ return enum_for(:each) { ngroup } unless block_given?
722
+ refuse_changed_rows("each")
723
+ ngroup.times { |k| yield @labels[k], @frame[group_address(k)] }
724
+ return self
725
+ end
726
+
284
727
  # Group key values (one per group), as an Array.
285
728
  def labels
286
729
  @labels.dup
@@ -367,12 +810,18 @@ class GroupedFrame
367
810
  cols = {}
368
811
  spec.each do |out_name, (in_name, reduction, *args)|
369
812
  out = @frame.__send__(:column_name_arg, out_name, "aggregate")
813
+ if in_name.is_a?(Symbol)
814
+ raise ArgumentError,
815
+ "aggregate: each entry is result name => [column, reduction] " \
816
+ "(got #{out_name.inspect} => #{spec[out_name].inspect}); " \
817
+ "as in aggregate(\"mean_#{out_name}\" => [#{out_name.inspect}, :mean])"
818
+ end
370
819
  @frame.__send__(:column_key, in_name, "aggregate")
371
820
  options = args.last.is_a?(Hash) ? args.pop : {}
372
821
  cols[out] =
373
822
  case reduction
374
823
  when Symbol
375
- group_reduce(@frame[in_name], reduction, *args, **options)
824
+ group_reduce(@frame.__send__(:named_column, in_name, "aggregate"), reduction, *args, **options)
376
825
  when Proc
377
826
  unless args.empty? && options.empty?
378
827
  raise ArgumentError, "aggregate: a Proc reduction takes no arguments (#{out.inspect})"
@@ -395,6 +844,7 @@ class GroupedFrame
395
844
  # first appear; a group whose Hash lacks a name is UNDEF there, as
396
845
  # +from_records+ reads a record that lacks a key.
397
846
  def table(keep_rows: false)
847
+ raise ArgumentError, "table: give a block" unless block_given?
398
848
  refuse_changed_rows("table")
399
849
  outs = []
400
850
  each_group_frame do |g|
@@ -426,20 +876,24 @@ class GroupedFrame
426
876
  # fills those columns only. +keep_rows: true+ gives each row its group's value
427
877
  # instead of one row per group, as for +aggregate+.
428
878
  #
429
- # Given column names, they reduce those columns only and return them as
430
- # +df[...]+ does: one name gives the CArray, several an Array of them.
879
+ # Given column names, they reduce those columns only, and the result is
880
+ # the frame of those columns, one row per group, labelled as above; with
881
+ # +keep_rows: true+ one comes back as +df[name]+ returns it, a CArray on
882
+ # the frame's rows, and several as a frame on those rows. For a group's
883
+ # values alone, reduce the column's group iterator: +grp["temp"].mean+.
431
884
  #
432
885
  # grp.mean # a frame, one row per group
433
- # grp.mean("temp") # CArray, one value per group
886
+ # grp.mean("temp") # a frame of temp, one row per group
434
887
  # df["temp"] - grp.mean("temp", keep_rows: true) # anomaly from the group mean
435
888
  #
436
889
  # @!method sum(*names, min_count: nil, fill_value: nil, keep_rows: false)
437
890
  # Returns a frame of the per-group sum of every column whose type has a
438
891
  # sum, an N-D one per group along the rows. Other columns are left out.
439
- # @return [CAFrame, CArray, Array<CArray>] a frame with one row per
440
- # group, indexed by the group labels, or with keep_rows: true the
441
- # frame's rows and index; given names, the CArray (one) or the Array of
442
- # them (several).
892
+ # @return [CAFrame, CArray] a frame with one row per
893
+ # group, indexed by the group labels (of the named columns when names
894
+ # are given), or with keep_rows: true the frame's rows and index; given
895
+ # names and keep_rows: true, the CArray (one) or a frame of them on the
896
+ # frame's rows (several).
443
897
  # @!method mean(*names, min_count: nil, fill_value: nil, keep_rows: false)
444
898
  # Returns a frame of the per-group mean of every column whose type has
445
899
  # a mean, as {#sum} does.
@@ -483,6 +937,43 @@ class GroupedFrame
483
937
  reduce_columns(red, names, keep_rows, min_count: min_count, fill_value: fill_value)
484
938
  end
485
939
 
940
+ # Each group's +p+-th percentile (0 to 100), as {#median} gives the 50th
941
+ # and {#sum} gives its sums. The percentage comes first, then the names.
942
+ #
943
+ # grp.percentile(90, "revenue")
944
+ #
945
+ # @param p [Numeric] the percentage.
946
+ # @param names [Array<String>] the columns; default every column that has
947
+ # a percentile.
948
+ # @return [CAFrame, CArray] one row per group, as {#sum} returns.
949
+ def percentile (p, *names, min_count: nil, fill_value: nil, keep_rows: false)
950
+ CAFrame.__send__(:check_percentage, p)
951
+ refuse_changed_rows(:percentile)
952
+ reduce_columns(:percentile, names, keep_rows, args: [p], min_count: min_count, fill_value: fill_value)
953
+ end
954
+
955
+ # Each group's five quartile percentiles, as +CAFrame#quantile+ gives them
956
+ # for all the rows: a column "x" gives "x_p0", "x_p25", "x_p50", "x_p75"
957
+ # and "x_p100", one row per group, labelled as {#sum} labels its result;
958
+ # with +keep_rows: true+ on the frame's rows.
959
+ #
960
+ # grp.quantile("temp")
961
+ #
962
+ # @param names [Array<String>] the columns; default every column that has
963
+ # a quantile.
964
+ # @return [CAFrame]
965
+ def quantile (*names, keep_rows: false)
966
+ refuse_changed_rows(:quantile)
967
+ refuse_key_as_result(:quantile, names) unless keep_rows
968
+ named = {}
969
+ over_named_columns(:quantile, names, @key_names) do |col, name|
970
+ named[name] = group_reduce(col, :quantile).map { |q| keep_rows ? spread_to_rows(q) : q }
971
+ end
972
+ cols = CAFrame.__send__(:quantile_columns, named)
973
+ return result_frame(cols, false) unless keep_rows
974
+ return CAFrame.new(cols, axis_name: @frame.axis_name, index: @frame.index&.copy)
975
+ end
976
+
486
977
  # The same convenience for the reductions that take no min_count: or
487
978
  # fill_value:, as the core ones take none: a value of the group (first,
488
979
  # last), a count (nunique, count) or a boolean fold (all, any).
@@ -522,8 +1013,8 @@ class GroupedFrame
522
1013
  # group's rows, a running statistic. A row in no group is UNDEF. Without
523
1014
  # names they give a frame of every column whose type has the operation
524
1015
  # (the key columns left out), on the frame's rows and index; given names,
525
- # the CArray (one) or the Array of them (several), as +df[...]+ returns
526
- # columns. An N-D column runs along the rows.
1016
+ # the CArray (one), as +df[name]+ returns a column, or a frame of those
1017
+ # columns (several) on the frame's rows and index. An N-D column runs along the rows.
527
1018
  #
528
1019
  # df["dtemp"] = df["temp"] - grp.lag("temp") # change since the station's previous row
529
1020
  # grp.order("temp", descending: true) # rank within the station
@@ -532,31 +1023,43 @@ class GroupedFrame
532
1023
  # "Previous" is the previous row of the frame: sort the frame first
533
1024
  # (+sort_by_key("time")+) when its rows are not in time order.
534
1025
  #
535
- # @!method lag(*names, n: 1)
1026
+ # @!method lag(*names, n: 1, before: nil, after: nil, on: nil)
536
1027
  # Returns each row's value +n+ rows back in its own group, UNDEF where
537
- # the group has none, as +CArray#lag+; a negative +n+ looks ahead.
538
- # @return [CAFrame, CArray, Array<CArray>]
1028
+ # the group has none, as +CArray#lag+; a negative +n+ looks ahead. With
1029
+ # +before:+ (or +after:+) instead, the value of the group's row whose key
1030
+ # (the index, or the column +on:+ names) is that distance earlier (or
1031
+ # later), as +CAFrame#lag+ gives it.
1032
+ # @return [CAFrame, CArray]
539
1033
  # @!method order(*names, descending: false, method: :ordinal, kind: :quick)
540
1034
  # Returns each row's rank among its group's rows (int64, 0 the
541
1035
  # smallest), as +CArray#order+ ranks them.
542
- # @return [CAFrame, CArray, Array<CArray>]
1036
+ # @return [CAFrame, CArray]
543
1037
  # @!method cumsum(*names)
544
1038
  # Returns the running sum within each group, as +CArray#cumsum+.
545
- # @return [CAFrame, CArray, Array<CArray>]
1039
+ # @return [CAFrame, CArray]
546
1040
  # @!method cumprod(*names)
547
1041
  # Returns the running product within each group.
548
- # @return [CAFrame, CArray, Array<CArray>]
1042
+ # @return [CAFrame, CArray]
549
1043
  # @!method cummax(*names)
550
1044
  # Returns the running maximum within each group.
551
- # @return [CAFrame, CArray, Array<CArray>]
1045
+ # @return [CAFrame, CArray]
552
1046
  # @!method cummin(*names)
553
1047
  # Returns the running minimum within each group.
554
- # @return [CAFrame, CArray, Array<CArray>]
1048
+ # @return [CAFrame, CArray]
555
1049
  # @!method cumcount(*names)
556
1050
  # Returns the running count of present values within each group (int64).
557
- # @return [CAFrame, CArray, Array<CArray>]
558
- def lag (*names, n: 1)
559
- transform_columns(:lag, names, [n], {})
1051
+ # @return [CAFrame, CArray]
1052
+ def lag (*names, n: nil, before: nil, after: nil, on: nil)
1053
+ distance = @frame.__send__(:lag_distance, "lag", n, before, after, on)
1054
+ return transform_columns(:lag, names, [n.nil? ? 1 : n], {}) if distance.nil?
1055
+ refuse_changed_rows("lag")
1056
+ refuse_key_on_rows(:lag, names)
1057
+ addr = @frame.__send__(:lag_addresses, "lag", (0...ngroup).map { |k| group_address(k) }, *distance)
1058
+ out = over_named_columns(:lag, names, @key_names | [distance.first], [1], {}) do |col|
1059
+ col[addr, *([nil] * (col.ndim - 1))].copy
1060
+ end
1061
+ return out if out.is_a?(CArray)
1062
+ CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index&.copy)
560
1063
  end
561
1064
 
562
1065
  def order (*names, descending: false, method: :ordinal, kind: :quick)
@@ -573,73 +1076,184 @@ class GroupedFrame
573
1076
  # Fill the masked cells of a column from the rows of the same group, in
574
1077
  # place, as +CAFrame#fill+ does for the whole column: +:ffill+ carries the
575
1078
  # group's last present value forward in row order, +:bfill+ its next one
576
- # back. A fill never reaches across into another group, so a cell with
577
- # nothing to carry in its group stays masked, and a row whose key is
578
- # masked (in no group) is left as it is. A constant fills every masked
579
- # cell, as +CAFrame#fill+ does. Returns self.
1079
+ # back, and +:linear+ interpolates between the group's present values
1080
+ # against the frame's index (against the row position within the group
1081
+ # when the frame has no index). A fill never reaches across into another
1082
+ # group, so a cell with nothing to carry or interpolate from in its group
1083
+ # stays masked, and a row whose key is masked (in no group) is left as it
1084
+ # is. A constant fills every masked cell, as +CAFrame#fill+ does. Returns
1085
+ # self.
580
1086
  #
581
1087
  # df.group_by("station").fill("temp", :ffill)
1088
+ # df.group_by("station").fill("temp", :linear)
1089
+ # df.group_by("station").fill("temp" => :linear, "rain" => 0.0)
1090
+ # df.group_by("station").fill("temp", "rain", :linear)
1091
+ # df.group_by("station").fill(:ffill) # every column with a masked cell
582
1092
  #
583
- # Sort the frame first (+sort_by_key("time")+) when its rows are not in
584
- # time order.
1093
+ # +:ffill+ and +:bfill+ follow the row order: sort the frame first
1094
+ # (+sort_by_key("time")+) when its rows are not in time order. +:linear+
1095
+ # reads each group in the order of the index, as +CAFrame#fill+ does.
585
1096
  #
586
- # @param name [String] the column.
587
- # @param method_or_value [Symbol, Object] +:ffill+, +:bfill+, or a constant.
1097
+ # @param args [Array] the columns, as +CAFrame#fill+ takes them, then
1098
+ # +:ffill+, +:bfill+, +:linear+, or a constant; or one Hash of them.
588
1099
  # @return [GroupedFrame] self
589
- # @raise [ArgumentError] for +:linear+, which within groups is not
590
- # provided, or another Symbol.
591
- def fill (name, method_or_value)
1100
+ # @raise [ArgumentError] for another Symbol, or for +:linear+ on a column
1101
+ # or index +CAFrame#fill+ cannot interpolate.
1102
+ def fill (*args)
1103
+ plan = @frame.__send__(:fill_arguments, args, @key_names)
1104
+ return self if plan.nil?
1105
+ refuse_key_on_rows(:fill, plan.is_a?(Hash) ? plan.keys : [plan.first])
1106
+ if plan.is_a?(Hash)
1107
+ @frame.__send__(:fill_by_map, plan, "fill") do |frame, key, how|
1108
+ grouped = if frame.equal?(@frame)
1109
+ self
1110
+ else
1111
+ # key-labels: the groups' index as it is, on a copy of the frame
1112
+ GroupedFrame.new(frame, @cat, @axis_name, @key_names, index: @index,
1113
+ label_columns: @label_columns)
1114
+ end
1115
+ grouped.fill(key, how)
1116
+ end
1117
+ return self
1118
+ end
1119
+ name, method_or_value = plan
592
1120
  refuse_changed_rows("fill")
593
1121
  case method_or_value
594
1122
  when :ffill, :bfill
595
1123
  @frame.__send__(:refuse_if_frozen)
596
1124
  key = @frame.__send__(:column_key, name, "fill")
597
- col = @frame[key]
1125
+ col = @frame.__send__(:named_column, key, "fill")
598
1126
  # A row in no group is UNDEF in the fill, so writing it changes nothing.
599
1127
  held = group_transform(col, :strip_mask, [], { method: method_or_value })
600
- target = col.is_masked
601
- col[target] = held[target] if target.any
1128
+ @frame.__send__(:write_filled_cells, col, held)
602
1129
  when :linear
603
- raise ArgumentError,
604
- "fill(#{name.inspect}, :linear): an interpolation within each group " \
605
- "is not provided; use :ffill or :bfill, or interpolate one group at a " \
606
- "time with CAFrame#fill"
1130
+ @frame.__send__(:refuse_if_frozen)
1131
+ key = @frame.__send__(:column_key, name, "fill")
1132
+ # The column and the index are checked as CAFrame#fill checks them,
1133
+ # on no rows, so a call without groups is refused as one with groups.
1134
+ @frame.__send__(:select_rows, CA_INT64([])).fill(key, :linear)
1135
+ # Each group's rows as a frame of views, so its fill writes through.
1136
+ ngroup.times do |k|
1137
+ @frame.__send__(:select_rows, group_address(k)).fill(key, :linear)
1138
+ end
607
1139
  when Symbol
608
1140
  raise ArgumentError,
609
1141
  "fill: unknown method #{method_or_value.inspect} " \
610
- "(:ffill | :bfill, or a constant fill value)"
1142
+ "(:ffill | :bfill | :linear, or a constant fill value)"
611
1143
  else
612
1144
  @frame.fill(name, method_or_value)
613
1145
  end
614
1146
  self
615
1147
  end
616
1148
 
1149
+ # The first +n+ rows of each group, in row order, as a view-frame: the
1150
+ # rows stay in the frame's order, as +filter+ keeps them. A group with
1151
+ # fewer than +n+ rows gives all of them; a row whose group key is masked
1152
+ # is in no group.
1153
+ #
1154
+ # df.group_by("station").head(1) # each station's first row
1155
+ #
1156
+ # @param n [Integer] how many rows per group, 0 or more (default 5).
1157
+ # @return [CAFrame]
1158
+ def head (n = 5)
1159
+ return rows_at_the_ends_of_groups("head", n) { |addr| addr.first(n) }
1160
+ end
1161
+
1162
+ # The last +n+ rows of each group, in row order, as +head+ gives the first.
1163
+ #
1164
+ # @param n [Integer] how many rows per group, 0 or more (default 5).
1165
+ # @return [CAFrame]
1166
+ def tail (n = 5)
1167
+ return rows_at_the_ends_of_groups("tail", n) { |addr| addr.last(n) }
1168
+ end
1169
+
1170
+ private def rows_at_the_ends_of_groups (verb, n)
1171
+ refuse_changed_rows(verb)
1172
+ unless n.is_a?(Integer)
1173
+ raise TypeError, "#{verb}: the count is an Integer (got #{n.inspect})"
1174
+ end
1175
+ raise ArgumentError, "#{verb}: the count must be 0 or more (got #{n})" if n < 0
1176
+ picked = (0...ngroup).flat_map { |k| yield(group_address(k).to_a) }.sort
1177
+ return @frame[CA_INT64(picked)]
1178
+ end
1179
+
1180
+ # The +n+ rows of each group with the largest values of the key columns,
1181
+ # as a view-frame: the groups in the order of +labels+, each group's rows
1182
+ # largest first, as +CAFrame#nlargest+ orders them (several keys break
1183
+ # ties in turn, a NaN or masked key loses to every value, rows that tie on
1184
+ # every key keep their order). A group with fewer than +n+ rows gives all
1185
+ # of them; a row whose group key is masked is in no group.
1186
+ #
1187
+ # df.group_by("station").nlargest(3, "temp") # each station's 3 warmest rows
1188
+ #
1189
+ # @param n [Integer] how many rows per group, 0 or more.
1190
+ # @param keys [Array<String>] the key columns (or the index axis name).
1191
+ # @return [CAFrame]
1192
+ # @raise [ArgumentError] when +n+ is negative or no key is given.
1193
+ def nlargest (n, *keys)
1194
+ return largest_rows_of_groups("nlargest", n, keys, true)
1195
+ end
1196
+
1197
+ # The +n+ rows of each group with the smallest values of the key columns,
1198
+ # as +nlargest+ gives the largest.
1199
+ #
1200
+ # @param n [Integer] how many rows per group, 0 or more.
1201
+ # @param keys [Array<String>] the key columns (or the index axis name).
1202
+ # @return [CAFrame]
1203
+ # @raise [ArgumentError] when +n+ is negative or no key is given.
1204
+ def nsmallest (n, *keys)
1205
+ return largest_rows_of_groups("nsmallest", n, keys, false)
1206
+ end
1207
+
1208
+ private def largest_rows_of_groups (verb, n, keys, descending)
1209
+ refuse_changed_rows(verb)
1210
+ unless n.is_a?(Integer)
1211
+ raise TypeError, "#{verb}: the count is an Integer (got #{n.inspect})"
1212
+ end
1213
+ raise ArgumentError, "#{verb}: the count must be 0 or more (got #{n})" if n < 0
1214
+ raise ArgumentError, "#{verb}: give at least one key column" if keys.empty?
1215
+ cols = keys.map do |key|
1216
+ @frame.__send__(:key_column, @frame.__send__(:column_key, key, verb), verb)
1217
+ end
1218
+ sort_keys = cols.map { |col| descending ? col.order(descending: true, method: :dense) : col }
1219
+ # Rows sorted by group, then by the keys; a row in no group comes last.
1220
+ addr = CArray.sort_addr(group_codes, *sort_keys, masked_position: :last).to_a
1221
+ picked = []
1222
+ start = 0
1223
+ @cat.category_sizes.to_a.each do |size|
1224
+ picked.concat(addr[start, [n, size].min]) if n > 0
1225
+ start += size
1226
+ end
1227
+ return @frame[CA_INT64(picked)]
1228
+ end
1229
+
617
1230
  # Keep the rows of the groups the block chooses. The block receives the
618
1231
  # grouped frame and returns a boolean CArray with one value per group,
619
1232
  # built from the group reductions, as +CAFrame#filter+'s block returns one
620
1233
  # per row:
621
1234
  #
622
1235
  # grp.filter { |g| g["temp"].count_not_masked >= 20 } # stations with 20 readings
623
- # grp.filter { |g| g.mean("temp") > 15.0 }
1236
+ # grp.filter { |g| g["temp"].mean > 15.0 }
624
1237
  #
625
1238
  # The rows of a chosen group are kept in the frame's order, as a sub-frame
626
1239
  # sharing the frame's columns. A group whose value is UNDEF is
627
1240
  # undetermined, as is a row whose key is masked (it belongs to no group):
628
- # such rows are dropped, or with +keep_masked: true+ carried with their
629
- # cells masked, as +CAFrame#filter+ does.
1241
+ # such rows are not kept, as +CAFrame#filter+ does not keep them.
630
1242
  #
631
- # @param keep_masked [Boolean] carry the undetermined rows forward masked.
632
1243
  # @yieldparam grouped [GroupedFrame] self.
633
1244
  # @yieldreturn [CArray] boolean, one value per group.
634
1245
  # @return [CAFrame]
635
1246
  # @raise [ArgumentError] when the block does not return a boolean CArray of
636
1247
  # shape [ngroup].
637
- def filter (keep_masked: false)
1248
+ def filter (**options)
1249
+ CAFrame.__send__(:refuse_filter_keywords, options, "filter")
1250
+ raise ArgumentError, "filter: give a block" unless block_given?
638
1251
  refuse_changed_rows("filter")
639
1252
  chosen = yield(self)
640
1253
  unless chosen.is_a?(CArray) && chosen.data_type == :boolean
641
1254
  raise ArgumentError,
642
- "filter block must return a boolean CArray (got #{chosen.is_a?(CArray) ? "a #{CArray::Inspector.type_label(chosen)} CArray" : chosen.class})"
1255
+ "filter block must return a boolean CArray (got #{chosen.is_a?(CArray) ? "a #{CArray::Inspector.type_label(chosen)} CArray" : chosen.class})" +
1256
+ CAFrame.__send__(:equality_hint, chosen)
643
1257
  end
644
1258
  unless chosen.shape == [ngroup]
645
1259
  raise ArgumentError,
@@ -647,7 +1261,7 @@ class GroupedFrame
647
1261
  "expected [#{ngroup}] (one value per group)"
648
1262
  end
649
1263
  rows = spread_to_rows(chosen)
650
- @frame.filter(keep_masked: keep_masked) { rows }
1264
+ @frame.filter(rows)
651
1265
  end
652
1266
 
653
1267
  # Returns the grouped rows as a frame: the frame the grouping was made
@@ -656,7 +1270,7 @@ class GroupedFrame
656
1270
  # rows; adding or dropping a column changes the new frame only.
657
1271
  #
658
1272
  # def warm_stations (grp)
659
- # grp.filter { |g| g.mean("temp") > 15.0 } # the rows of some groups
1273
+ # grp.filter { |g| g["temp"].mean > 15.0 } # the rows of some groups
660
1274
  # end
661
1275
  # grp.to_frame # all of its rows
662
1276
  #
@@ -677,48 +1291,83 @@ class GroupedFrame
677
1291
  # would otherwise leave every column out without a word.
678
1292
  private def transform_columns(op, names, args, keywords)
679
1293
  refuse_changed_rows(op)
1294
+ refuse_key_on_rows(op, names)
680
1295
  CArray.float64(1).public_send(op, *args, **keywords)
681
1296
  out = over_named_columns(op, names, @key_names, args, keywords) do |col|
682
1297
  group_transform(col, op, args, keywords)
683
1298
  end
684
- return out unless names.empty?
685
- CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index)
1299
+ refuse_no_column_on_rows(op, out, @frame.nrow)
1300
+ return out if out.is_a?(CArray)
1301
+ CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index&.copy)
686
1302
  end
687
1303
 
688
1304
  # A column's within-group transform: an N-D column runs along the rows.
689
1305
  private def group_transform(col, op, args, keywords)
1306
+ return group_lag_by_rows(col, *args) if op == :lag && col.face? && !col.__send__(:holds_new_values?)
690
1307
  it = col.group_by_category(@cat)
691
1308
  keywords = keywords.merge(axis: 0) if col.ndim > 1
692
1309
  it.public_send(op, *args, **keywords)
693
1310
  end
694
1311
 
1312
+ # A Face that cannot hold new values answers an iterator's lag in object
1313
+ # cells. Reading each cell from the row it lags keeps the Face, as
1314
+ # lag(before:) does.
1315
+ private def group_lag_by_rows(col, step)
1316
+ rows = CArray.int64(@frame.nrow).seq.group_by_category(@cat).lag(step)
1317
+ col[rows, *([nil] * (col.ndim - 1))].copy
1318
+ end
1319
+
695
1320
  # Each result gets its own index.
696
1321
  private def label_index
697
1322
  return @index.copy if @index
698
1323
  CArray.object(@labels.size) { |i| @labels[i] }
699
1324
  end
700
1325
 
701
- # A key column is the index here, not a result column. Named columns
702
- # come back as df[...] returns them, each on the frame's rows with
703
- # +keep_rows+.
704
- private def reduce_columns(reduction, names, keep_rows, **keywords)
1326
+ # A key column is the index here, not a result column. Named columns give
1327
+ # the frame of those columns only, one row per group; with +keep_rows+
1328
+ # they come back as df[...] returns them, each on the frame's rows.
1329
+ private def reduce_columns(reduction, names, keep_rows, args: [], **keywords)
1330
+ refuse_key_as_result(reduction, names) unless keep_rows
705
1331
  keywords = keywords.compact
706
1332
  fills = keywords.delete(:fill_value)
707
- if fills.is_a?(Hash)
708
- unknown = fills.keys - @frame.column_names
709
- unless unknown.empty?
710
- raise ArgumentError,
711
- "#{reduction}: fill_value names no column #{unknown.map(&:inspect).join(', ')}"
712
- end
713
- end
714
- out = over_named_columns(reduction, names, @key_names) do |col, name|
1333
+ refuse_unknown_fill_columns(reduction, fills)
1334
+ refuse_wrong_reduction_arguments(reduction, args, keywords)
1335
+ named = {}
1336
+ out = over_named_columns(reduction, names, @key_names, args) do |col, name|
715
1337
  fill = fills.is_a?(Hash) ? fills[name] : fills
716
1338
  kw = fill.nil? ? keywords : keywords.merge(fill_value: fill)
717
- col = group_reduce(col, reduction, **kw)
718
- keep_rows && !names.empty? ? spread_to_rows(col) : col
1339
+ col = group_reduce(col, reduction, *args, **kw)
1340
+ named[name] = keep_rows && !names.empty? ? spread_to_rows(col) : col
719
1341
  end
720
- return out unless names.empty?
721
- result_frame(out, keep_rows)
1342
+ return result_frame(out, keep_rows) if names.empty?
1343
+ # One named column on the frame's rows comes back as df[name] returns it,
1344
+ # several as a frame on those rows; one value per group needs the group
1345
+ # labels beside it.
1346
+ if keep_rows
1347
+ return out if out.is_a?(CArray)
1348
+ return CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index&.copy)
1349
+ end
1350
+ result_frame(named, false)
1351
+ end
1352
+
1353
+ # A key column named in a reduction would be a result column beside the
1354
+ # key it is the group of: the index, or a key column of the result.
1355
+ private def refuse_key_as_result(reduction, names)
1356
+ named = names.map { |n| n.is_a?(String) ? n : nil }.compact & @key_names
1357
+ return if named.empty?
1358
+ hint = reduction == :count ? "; the number of rows of each group is size" : ""
1359
+ raise ArgumentError,
1360
+ "#{reduction}: #{named.first.inspect} is the group key, already in the result#{hint}"
1361
+ end
1362
+
1363
+ # A key column named in a verb computed within each group: the key holds
1364
+ # one value in a group, so there is nothing to compute along it, and a
1365
+ # fill would write to what the groups were made from.
1366
+ private def refuse_key_on_rows(verb, names)
1367
+ named = names.map { |n| n.is_a?(String) ? n : nil }.compact & @key_names
1368
+ return if named.empty?
1369
+ raise ArgumentError,
1370
+ "#{verb}: #{named.first.inspect} is the group key, one value within each group"
722
1371
  end
723
1372
 
724
1373
  # One row per group, indexed by the labels; or, with +keep_rows+, the
@@ -734,7 +1383,7 @@ class GroupedFrame
734
1383
  return CAFrame.new(@label_columns.transform_values(&:copy).merge(cols))
735
1384
  end
736
1385
  CAFrame.new(cols.transform_values { |col| spread_to_rows(col) },
737
- axis_name: @frame.axis_name, index: @frame.index)
1386
+ axis_name: @frame.axis_name, index: @frame.index&.copy)
738
1387
  end
739
1388
 
740
1389
  # A per-group result (one entry per group along axis 0) laid back over the
@@ -751,6 +1400,10 @@ class GroupedFrame
751
1400
  # A column's group reduction. An N-D column is reduced along the rows, so
752
1401
  # each group keeps the trailing shape: a profile column (N, L) gives (G, L).
753
1402
  private def group_reduce(col, reduction, *args, **keywords)
1403
+ if %i[first last].include?(reduction) && col.ndim == 1 && args.empty? && keywords.empty? &&
1404
+ col.face? && !col.__send__(:holds_new_values?)
1405
+ return col[present_rows(col).group_by_category(@cat).public_send(reduction)].copy
1406
+ end
754
1407
  it = col.group_by_category(@cat)
755
1408
  if col.ndim > 1 && !keywords.key?(:axis)
756
1409
  it.public_send(reduction, *args, axis: 0, **keywords)
@@ -802,7 +1455,7 @@ class GroupedFrame
802
1455
  end
803
1456
 
804
1457
  private def each_group_slice(in_name)
805
- col = @frame[in_name]
1458
+ col = @frame.__send__(:named_column, in_name, "aggregate")
806
1459
  ngroup.times do |k|
807
1460
  yield col[group_address(k), *([nil] * (col.ndim - 1))]
808
1461
  end