carray 3.0.6 → 3.1.0

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 (277) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +1 -1
  3. data/CHANGELOG.md +7 -1830
  4. data/README.md +62 -35
  5. data/carray.gemspec +16 -4
  6. data/docs/changelogs/CHANGELOG-3.0.md +2464 -0
  7. data/ext/ca_array_pool.c +4 -5
  8. data/ext/ca_axis_descriptor.h +45 -30
  9. data/ext/ca_axis_dispatch.c +7 -4
  10. data/ext/ca_axis_group.c +12 -15
  11. data/ext/ca_bincmp_dispatch.h +16 -38
  12. data/ext/ca_binop_dispatch.c +35 -0
  13. data/ext/ca_binop_dispatch.h +22 -46
  14. data/ext/ca_categorical_iterator.c +36 -34
  15. data/ext/ca_compare.c +0 -1
  16. data/ext/ca_compare.h +8 -1
  17. data/ext/ca_composite_dispatch.h +6 -0
  18. data/ext/ca_for_buffer.h +6 -1
  19. data/ext/ca_group_iter.c +17 -18
  20. data/ext/ca_iter_state_fields.h +196 -0
  21. data/ext/ca_iter_substrate.h +84 -103
  22. data/ext/ca_kernel_iterator.c +125 -89
  23. data/ext/ca_kernel_iterator.h +229 -1504
  24. data/ext/ca_kernel_iterator_internal.h +1167 -0
  25. data/ext/ca_moncmp_dispatch.h +17 -24
  26. data/ext/ca_monop_dispatch.h +25 -74
  27. data/ext/ca_obj_array.c +92 -165
  28. data/ext/ca_obj_bincmp.c +65 -48
  29. data/ext/ca_obj_binop.c +74 -49
  30. data/ext/ca_obj_bitarray.c +7 -21
  31. data/ext/ca_obj_bitfield.c +93 -26
  32. data/ext/ca_obj_block.c +11 -12
  33. data/ext/ca_obj_byte_swap.c +34 -34
  34. data/ext/ca_obj_const_string.c +464 -304
  35. data/ext/ca_obj_face.c +167 -121
  36. data/ext/ca_obj_face.h +32 -170
  37. data/ext/ca_obj_fake.c +127 -34
  38. data/ext/ca_obj_farray.c +13 -9
  39. data/ext/ca_obj_field.c +17 -13
  40. data/ext/ca_obj_fixlen_string.c +57 -34
  41. data/ext/ca_obj_grid.c +149 -113
  42. data/ext/ca_obj_meld.c +28 -26
  43. data/ext/ca_obj_moncmp.c +10 -21
  44. data/ext/ca_obj_monop.c +88 -73
  45. data/ext/ca_obj_object.c +60 -46
  46. data/ext/ca_obj_record.c +74 -22
  47. data/ext/ca_obj_reduce.c +10 -14
  48. data/ext/ca_obj_refer.c +146 -39
  49. data/ext/ca_obj_remap.c +11 -29
  50. data/ext/ca_obj_repeat.c +41 -23
  51. data/ext/ca_obj_roll.c +20 -28
  52. data/ext/ca_obj_select.c +17 -27
  53. data/ext/ca_obj_select_axis.c +35 -42
  54. data/ext/ca_obj_shift.c +22 -42
  55. data/ext/ca_obj_source.c +1 -5
  56. data/ext/ca_obj_stack.c +33 -29
  57. data/ext/ca_obj_stride.c +99 -62
  58. data/ext/ca_obj_string.c +8 -20
  59. data/ext/ca_obj_tile.c +14 -16
  60. data/ext/ca_obj_time.c +12 -23
  61. data/ext/ca_obj_timedelta.c +12 -23
  62. data/ext/ca_obj_transpose.c +8 -10
  63. data/ext/ca_obj_triop.c +48 -49
  64. data/ext/ca_obj_window.c +87 -99
  65. data/ext/ca_op_cmplx64.h +4 -0
  66. data/ext/ca_op_ipower.c +97 -27
  67. data/ext/ca_op_powi.h +9 -28
  68. data/ext/ca_pow5_table.h +2 -1
  69. data/ext/ca_rng_normal.h +4 -0
  70. data/ext/ca_rng_xoshiro256pp.h +3 -0
  71. data/ext/ca_sort_kernels.h +23 -26
  72. data/ext/ca_sweep_engine.c +92 -26
  73. data/ext/ca_sweep_engine.h +22 -15
  74. data/ext/ca_transform_common.c +3 -8
  75. data/ext/ca_triop_dispatch.h +20 -32
  76. data/ext/caframe_csv_reader.c +12 -12
  77. data/ext/carray.h +300 -1009
  78. data/ext/carray_access.c +320 -207
  79. data/ext/carray_address_basis.c +128 -59
  80. data/ext/carray_attribute.c +81 -104
  81. data/ext/carray_bincount.c +12 -14
  82. data/ext/carray_broadcast.c +31 -27
  83. data/ext/carray_call_cfunc.c +174 -285
  84. data/ext/carray_call_cfunc.h +36 -28
  85. data/ext/carray_cast.c +1191 -351
  86. data/ext/carray_cast_func.rb +68 -8
  87. data/ext/carray_class.c +6 -11
  88. data/ext/carray_conversion.c +98 -39
  89. data/ext/carray_copy.c +52 -26
  90. data/ext/carray_core.c +286 -132
  91. data/ext/carray_count.c +53 -22
  92. data/ext/carray_element.c +49 -28
  93. data/ext/carray_factorize.c +64 -63
  94. data/ext/carray_generate.c +26 -19
  95. data/ext/carray_histogram.c +9 -11
  96. data/ext/carray_hold.c +7 -9
  97. data/ext/carray_index_classifier.c +127 -230
  98. data/ext/carray_index_classifier.h +11 -10
  99. data/ext/carray_integer_total.c +523 -0
  100. data/ext/carray_internal.h +1364 -156
  101. data/ext/carray_key_windows.c +3 -3
  102. data/ext/carray_lazy.c +37 -37
  103. data/ext/carray_loop.c +27 -23
  104. data/ext/carray_mask.c +235 -150
  105. data/ext/carray_math_kernel.h +23 -47
  106. data/ext/carray_mathfunc.c +10 -3
  107. data/ext/carray_median_percentile.c +106 -100
  108. data/ext/carray_memory_view.c +83 -69
  109. data/ext/carray_operator.c +490 -128
  110. data/ext/carray_order.c +163 -84
  111. data/ext/carray_partition.c +14 -16
  112. data/ext/carray_random.c +48 -42
  113. data/ext/carray_round.c +33 -5
  114. data/ext/carray_scatter.c +57 -39
  115. data/ext/carray_segment.c +42 -46
  116. data/ext/carray_slab.c +77 -51
  117. data/ext/carray_slab.h +44 -33
  118. data/ext/carray_sort.c +37 -31
  119. data/ext/carray_sort_kernel.c +36 -10
  120. data/ext/carray_struct.c +44 -34
  121. data/ext/carray_test.c +131 -81
  122. data/ext/carray_time_text.c +30 -31
  123. data/ext/carray_undef.c +50 -7
  124. data/ext/carray_utils.c +373 -139
  125. data/ext/extconf.rb +24 -17
  126. data/ext/mk_call_cfunc.rb +25 -31
  127. data/ext/mk_pow5_table.rb +2 -1
  128. data/ext/mkkernel.rb +819 -488
  129. data/ext/ruby_carray.c +47 -42
  130. data/ext/version.h +7 -5
  131. data/lib/carray/attribute.rb +19 -18
  132. data/lib/carray/autoload_carray.rb +20 -15
  133. data/lib/carray/autoload_method_extension.rb +64 -57
  134. data/lib/carray/axis_group.rb +272 -185
  135. data/lib/carray/basics.rb +298 -56
  136. data/lib/carray/bincount_nd.rb +41 -18
  137. data/lib/carray/block_iterator.rb +167 -119
  138. data/lib/carray/boolean_reduce.rb +7 -4
  139. data/lib/carray/categorical.rb +84 -59
  140. data/lib/carray/categorical_iterator.rb +90 -67
  141. data/lib/carray/complex.rb +61 -41
  142. data/lib/carray/conditional.rb +98 -23
  143. data/lib/carray/const_string.rb +112 -46
  144. data/lib/carray/core_extensions.rb +20 -69
  145. data/lib/carray/distance_limit.rb +7 -5
  146. data/lib/carray/factories.rb +269 -0
  147. data/lib/carray/fixlen_string.rb +95 -12
  148. data/lib/carray/frame/column_verbs.rb +76 -9
  149. data/lib/carray/frame/concat.rb +51 -7
  150. data/lib/carray/frame/convert.rb +2 -1
  151. data/lib/carray/frame/csv_parser.rb +20 -5
  152. data/lib/carray/frame/frame.rb +73 -31
  153. data/lib/carray/frame/group.rb +247 -187
  154. data/lib/carray/frame/io.rb +36 -12
  155. data/lib/carray/frame/join.rb +56 -17
  156. data/lib/carray/frame/records.rb +7 -5
  157. data/lib/carray/frame/reshape.rb +27 -7
  158. data/lib/carray/frame/sort.rb +10 -8
  159. data/lib/carray/frame/verbs.rb +217 -134
  160. data/lib/carray/frame/windows.rb +254 -19
  161. data/lib/carray/frame.rb +1 -2
  162. data/lib/carray/fuse_source.rb +28 -23
  163. data/lib/carray/fusion.rb +30 -30
  164. data/lib/carray/histogram.rb +35 -16
  165. data/lib/carray/inspect.rb +7 -7
  166. data/lib/carray/iterator.rb +104 -23
  167. data/lib/carray/key_windows.rb +93 -61
  168. data/lib/carray/lazy.rb +208 -111
  169. data/lib/carray/limits.rb +80 -0
  170. data/lib/carray/mask_gap_fill.rb +21 -16
  171. data/lib/carray/math.rb +87 -50
  172. data/lib/carray/meld_reduce.rb +30 -8
  173. data/lib/carray/methods/align_addr.rb +29 -17
  174. data/lib/carray/methods/bin.rb +8 -1
  175. data/lib/carray/methods/bincount.rb +4 -2
  176. data/lib/carray/methods/bit_string.rb +19 -31
  177. data/lib/carray/methods/broadcast.rb +8 -3
  178. data/lib/carray/methods/choose.rb +5 -5
  179. data/lib/carray/methods/composition.rb +73 -72
  180. data/lib/carray/methods/{index.rb → coordinate.rb} +13 -13
  181. data/lib/carray/methods/discovery_along.rb +3 -3
  182. data/lib/carray/methods/factorize.rb +2 -0
  183. data/lib/carray/methods/gather_nd.rb +106 -103
  184. data/lib/carray/methods/insert_block.rb +2 -2
  185. data/lib/carray/methods/is_between.rb +6 -4
  186. data/lib/carray/methods/is_in.rb +183 -143
  187. data/lib/carray/methods/join.rb +2 -1
  188. data/lib/carray/methods/lag.rb +6 -2
  189. data/lib/carray/methods/locate_addr.rb +157 -94
  190. data/lib/carray/methods/mask_duplicates.rb +1 -1
  191. data/lib/carray/methods/meshgrid.rb +28 -16
  192. data/lib/carray/methods/mode.rb +67 -67
  193. data/lib/carray/methods/nunique.rb +9 -7
  194. data/lib/carray/methods/repeat.rb +23 -13
  195. data/lib/carray/methods/resize.rb +1 -1
  196. data/lib/carray/methods/snap.rb +24 -20
  197. data/lib/carray/methods/string_format.rb +2 -2
  198. data/lib/carray/methods/unique.rb +4 -2
  199. data/lib/carray/methods/value_counts.rb +1 -1
  200. data/lib/carray/mkmf.rb +25 -28
  201. data/lib/carray/percentile_arguments.rb +82 -0
  202. data/lib/carray/record_order.rb +50 -20
  203. data/lib/carray/rng.rb +1 -0
  204. data/lib/carray/runtime.rb +195 -17
  205. data/lib/carray/segment_iterator.rb +262 -137
  206. data/lib/carray/serialize.rb +635 -566
  207. data/lib/carray/slab_iterator.rb +114 -114
  208. data/lib/carray/stack.rb +14 -15
  209. data/lib/carray/string.rb +16 -22
  210. data/lib/carray/string_operation_extension.rb +97 -52
  211. data/lib/carray/struct.rb +122 -164
  212. data/lib/carray/struct_builder.rb +247 -73
  213. data/lib/carray/time.rb +663 -365
  214. data/lib/carray/window_iterator.rb +232 -155
  215. data/lib/carray.rb +6 -11
  216. data/yard-stubs/ca_obj_array.rb +20 -135
  217. data/yard-stubs/ca_obj_bitarray.rb +1 -8
  218. data/yard-stubs/ca_obj_bitfield.rb +6 -2
  219. data/yard-stubs/ca_obj_byte_swap.rb +21 -7
  220. data/yard-stubs/ca_obj_fake.rb +3 -1
  221. data/yard-stubs/ca_obj_farray.rb +1 -1
  222. data/yard-stubs/ca_obj_field.rb +8 -6
  223. data/yard-stubs/ca_obj_refer.rb +10 -5
  224. data/yard-stubs/ca_obj_roll.rb +7 -6
  225. data/yard-stubs/ca_obj_shift.rb +2 -3
  226. data/yard-stubs/ca_obj_stride.rb +5 -7
  227. data/yard-stubs/ca_obj_tile.rb +1 -1
  228. data/yard-stubs/ca_obj_time.rb +43 -0
  229. data/yard-stubs/ca_obj_transpose.rb +1 -1
  230. data/yard-stubs/ca_obj_window.rb +28 -16
  231. data/yard-stubs/carray_access.rb +55 -6
  232. data/yard-stubs/carray_attribute.rb +26 -38
  233. data/yard-stubs/carray_cast.rb +121 -162
  234. data/yard-stubs/carray_class.rb +3 -4
  235. data/yard-stubs/carray_conversion.rb +6 -7
  236. data/yard-stubs/carray_copy.rb +2 -1
  237. data/yard-stubs/carray_count.rb +10 -5
  238. data/yard-stubs/carray_element.rb +4 -3
  239. data/yard-stubs/carray_limits.rb +100 -0
  240. data/yard-stubs/carray_loop.rb +0 -20
  241. data/yard-stubs/carray_mask.rb +59 -41
  242. data/yard-stubs/carray_math.rb +162 -100
  243. data/yard-stubs/carray_mathfunc.rb +415 -3
  244. data/yard-stubs/carray_median_percentile.rb +29 -11
  245. data/yard-stubs/carray_memory_view.rb +2 -2
  246. data/yard-stubs/carray_order.rb +72 -33
  247. data/yard-stubs/carray_random.rb +6 -6
  248. data/yard-stubs/carray_reduce.rb +353 -0
  249. data/yard-stubs/carray_rng.rb +92 -0
  250. data/yard-stubs/carray_scatter.rb +12 -3
  251. data/yard-stubs/carray_slab.rb +7 -4
  252. data/yard-stubs/carray_sort.rb +7 -6
  253. data/yard-stubs/carray_test.rb +18 -5
  254. data/yard-stubs/carray_undef.rb +44 -5
  255. data/yard-stubs/ruby_carray.rb +75 -40
  256. metadata +63 -25
  257. data/CHANGELOG.v1.md +0 -126
  258. data/ext/carray_build_flags.h +0 -3
  259. data/ext/carray_config.h +0 -28
  260. data/ext/carray_data_type.c +0 -90
  261. data/ext/carray_kernels_bincmp.c +0 -6457
  262. data/ext/carray_kernels_binop.c +0 -31534
  263. data/ext/carray_kernels_init.c +0 -1734
  264. data/ext/carray_kernels_moncmp.c +0 -2104
  265. data/ext/carray_kernels_monop.c +0 -25387
  266. data/ext/carray_kernels_reduce_aggregate.c +0 -27545
  267. data/ext/carray_kernels_reduce_boolean.c +0 -1924
  268. data/ext/carray_kernels_reduce_cumulative.c +0 -11646
  269. data/ext/carray_kernels_reduce_extreme.c +0 -21631
  270. data/ext/carray_kernels_reduce_variance.c +0 -5981
  271. data/ext/carray_kernels_scan.c +0 -4302
  272. data/ext/carray_kernels_search.c +0 -37776
  273. data/ext/carray_kernels_sort.c +0 -10814
  274. data/ext/carray_kernels_triop.c +0 -1864
  275. data/lib/carray/construct.rb +0 -360
  276. data/lib/carray/data_type_extension.rb +0 -261
  277. data/lib/carray/data_type_limits.rb +0 -91
@@ -1,4 +1,4 @@
1
- # CAFrame group_by (memo §5 spine, §11.6 surface).
1
+ # CAFrame group_by (memo §5 core, §11.6 surface).
2
2
  #
3
3
  # Grouping is always on the row axis (axis 0). The key is any length-N
4
4
  # thing: a column name, several column names (composite key), or an
@@ -20,12 +20,12 @@ class CAFrame
20
20
  # df.value_counts("station")
21
21
  # df.value_counts("station", "weather", sort: :value)
22
22
  #
23
- # The columns are given as +select+ takes them. +group_by(...).size+ is the
23
+ # The columns are given as +select+ takes them. +group_by(...).group_sizes+ is the
24
24
  # same count in the order of the groups.
25
25
  #
26
26
  # @return [CAFrame]
27
27
  # @raise [ArgumentError] for another +sort:+, or a +name:+ a key has.
28
- def value_counts (*names, sort: :count, name: "count")
28
+ def value_counts(*names, sort: :count, name: "count")
29
29
  unless [:count, :value, false].include?(sort)
30
30
  raise ArgumentError, "value_counts: sort: is :count, :value or false (got #{sort.inspect})"
31
31
  end
@@ -40,7 +40,7 @@ class CAFrame
40
40
  "value_counts: a counted column is named #{name.inspect}; name the count " \
41
41
  "otherwise, as in value_counts(..., name: \"n\")"
42
42
  end
43
- out = group_by(*keys).size(name: name)
43
+ out = group_by(*keys).group_sizes(name: name)
44
44
  case sort
45
45
  when :count then out.sort_by_key(name, descending: true)
46
46
  when :value
@@ -54,11 +54,11 @@ class CAFrame
54
54
  else out
55
55
  end
56
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
57
+ raise e.class, e.message.sub(/\A(group_by|group_sizes|sort_by_key):/, "value_counts:"), e.backtrace
58
58
  end
59
59
 
60
60
  # Group rows by one or more keys. Each key is a column name (String) or an
61
- # external length-N CArray. Returns a GroupedFrame.
61
+ # external length-N CArray. Returns a CAGroupedFrame.
62
62
  #
63
63
  # With one key, a summary's index is the key's value of each group. With
64
64
  # several, each key is a column of a summary, holding its part of each
@@ -70,11 +70,11 @@ class CAFrame
70
70
  cat = grouping_categorical(keys)
71
71
  if keys.size == 1
72
72
  axis = keys.first.is_a?(String) ? keys.first : "group"
73
- return GroupedFrame.new(self, cat, axis, keys.grep(String), key: key_column(keys.first))
73
+ return CAGroupedFrame.new(self, cat, axis, keys.grep(String), key: key_column(keys.first))
74
74
  end
75
75
  names = keys.each_with_index.map { |k, i| k.is_a?(String) ? k : "key#{i}" }
76
76
  CAFrame.__send__(:refuse_repeated_names, names, "group_by")
77
- GroupedFrame.new(self, cat, "group", keys.grep(String),
77
+ CAGroupedFrame.new(self, cat, "group", keys.grep(String),
78
78
  key_columns: names.zip(keys.map { |k| key_column(k) }).to_h)
79
79
  end
80
80
 
@@ -128,10 +128,10 @@ class CAFrame
128
128
  end
129
129
 
130
130
  # Group rows into time bins of length +unit+ along the time column (or the
131
- # time index) +name+, for the reductions GroupedFrame offers:
131
+ # time index) +name+, for the reductions CAGroupedFrame offers:
132
132
  #
133
133
  # df.resample("time", "1 hour").mean
134
- # df.resample("time", "1 day", fill: true).aggregate("rain" => ["rain", :sum])
134
+ # df.resample("time", "1 day", keep_empty: true).aggregate("rain" => ["rain", :sum])
135
135
  #
136
136
  # The result's index is the bin labels as a CATime, in time order, and its
137
137
  # row axis is named after +name+.
@@ -143,16 +143,16 @@ class CAFrame
143
143
  # describes the hour before it. +origin:+ shifts the bins as +CATime#floor+
144
144
  # does ("1 hour" with origin 00:30 gives 00:30, 01:30, ...).
145
145
  #
146
- # Without +fill:+, a bin with no rows does not appear. With +fill: true+
147
- # every bin from the first to the last is a row, and an empty one reduces
148
- # as an empty reduction does: UNDEF for +mean+, 0 for +count+ and +sum+.
146
+ # Without +keep_empty:+, a bin with no rows does not appear. With
147
+ # +keep_empty: true+ every bin from the first to the last is a row, and an
148
+ # empty one reduces as an empty reduction does: UNDEF for +mean+, 0 for +count+ and +sum+.
149
149
  # A row whose time is masked belongs to no bin.
150
150
  #
151
- # +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
152
152
  # own: a group is the rows sharing the +by:+ values and a bin. The result
153
153
  # then has no index: the +by:+ columns and the bin times (named +name+)
154
154
  # are its first columns, the groups in the order their +by:+ values first
155
- # appear and the bins of each in time order. With +fill: true+ every group
155
+ # appear and the bins of each in time order. With +keep_empty: true+ every group
156
156
  # has every bin from the first to the last of the whole frame. A row whose
157
157
  # +by:+ value is masked belongs to no group.
158
158
  #
@@ -162,12 +162,18 @@ class CAFrame
162
162
  # @param unit [String, Symbol, CATime::Resolution] the bin length.
163
163
  # @param origin [nil, Time, String, CATime::Element] where bins start.
164
164
  # @param label [:left, :right] which end of a bin names it and is closed.
165
- # @param fill [Boolean] whether bins with no rows are rows of the result.
166
- # @param by [nil, String, Array<String>] columns whose groups are binned apart.
167
- # @return [GroupedFrame]
165
+ # @param keep_empty [Boolean] whether bins with no rows are rows of the
166
+ # result.
167
+ # @param by [nil, String, CArray, Array<String, CArray>] columns whose groups
168
+ # are binned apart; a CArray key (one value per row, as group_by takes it)
169
+ # is labelled "key0", "key1", ... by its place.
170
+ # @return [CAGroupedFrame]
168
171
  # @raise [ArgumentError] when the column is not a CATime, or +label:+ is
169
172
  # neither :left nor :right, or +by:+ names the time column.
170
- def resample(name, unit, origin: nil, label: :left, fill: false, by: nil)
173
+ def resample(name, unit, origin: nil, label: :left, keep_empty: false, by: nil)
174
+ keep_empty = CArray.send(:bool_arg, keep_empty, "keep_empty", "resample")
175
+ # A Grid is read as its (unit, origin) pair, which every step below takes.
176
+ unit, origin = CATime::Grid.resolve(unit, origin, "resample")
171
177
  name = column_key(name, "resample")
172
178
  time = key_column(name, "resample")
173
179
  unless time.is_a?(CATime)
@@ -181,30 +187,35 @@ class CAFrame
181
187
  raise ArgumentError, "resample: label: must be :left or :right (got #{label.inspect})"
182
188
  end
183
189
  # key-labels: the bins are the index, given the column's attributes below.
184
- grid = fill && bins.count_not_masked > 0 ? resample_grid(bins, unit) : bins.unique(sort: true)
185
- return resample_by(name, time, bins, grid, by, fill) unless by.nil?
190
+ grid = keep_empty && bins.count_not_masked > 0 ? resample_grid(bins, unit) : bins.unique(sort: true)
191
+ return resample_by(name, time, bins, grid, by, keep_empty) unless by.nil?
186
192
  cat = CACategorical.from_codes(bins.locate_addr(grid), grid.to_a)
187
- GroupedFrame.new(self, cat, name, @columns.key?(name) ? [name] : [],
193
+ CAGroupedFrame.new(self, cat, name, @columns.key?(name) ? [name] : [],
188
194
  index: CAFrame.__send__(:key_labels, time, grid))
189
195
  end
190
196
 
191
197
  # resample with by:. A group is a (by values, bin) pair, coded as
192
198
  # group * bins + bin, so the codes run through the groups in the order their
193
199
  # by values first appear and through each group's bins in time order.
194
- private def resample_by(name, time, bins, grid, by, fill)
195
- by_names = column_keys(Array(by), "resample")
196
- raise ArgumentError, "resample: by: names no column" if by_names.empty?
197
- if by_names.include?(name)
200
+ # A by: key is a column name or, as group_by takes it, a CArray of one
201
+ # value per row; a CArray key is labelled "key0", "key1", ... by its place.
202
+ private def resample_by(name, time, bins, grid, by, keep_empty)
203
+ keys = by.is_a?(Array) ? by : [by]
204
+ raise ArgumentError, "resample: by: names no column" if keys.empty?
205
+ keys.each { |k| column_key(k, "resample") unless k.is_a?(CArray) }
206
+ if keys.include?(name)
198
207
  raise ArgumentError, "resample: by: names the time column #{name.inspect}"
199
208
  end
200
- by_cols = by_names.map { |n| key_column(n, "resample") }
209
+ by_names = keys.each_with_index.map { |k, i| k.is_a?(String) ? k : "key#{i}" }
210
+ CAFrame.__send__(:refuse_repeated_names, by_names + [name], "resample")
211
+ by_cols = keys.map { |k| key_column(k, "resample") }
201
212
  gcat = CACategorical.send(:from_keys, by_cols)
202
213
  ng = gcat.labels.size
203
214
  nb = grid.elements
204
215
  comb = gcat.codes.int64 * nb + bins.locate_addr(grid).int64
205
216
  # key-labels: the used (group, bin) codes, not labels; those go through key_labels below
206
- occupied = fill ? CArray.int64(ng * nb).seq! : comb.unique(sort: true)
207
- codes = fill ? comb : comb.locate_addr(occupied)
217
+ occupied = keep_empty ? CArray.int64(ng * nb).seq! : comb.unique(sort: true)
218
+ codes = keep_empty ? comb : comb.locate_addr(occupied)
208
219
  g_of = nb > 0 ? occupied / nb : occupied
209
220
  b_of = nb > 0 ? occupied % nb : occupied
210
221
  # Each group's by values, from its first row.
@@ -223,19 +234,29 @@ class CAFrame
223
234
  parts + [blabels[b]]
224
235
  end
225
236
  cat = CACategorical.from_codes(codes, labels)
226
- key_names = by_names + (@columns.key?(name) ? [name] : [])
227
- GroupedFrame.new(self, cat, "group", key_names, label_columns: columns)
237
+ key_names = keys.grep(String) + (@columns.key?(name) ? [name] : [])
238
+ CAGroupedFrame.new(self, cat, "group", key_names, label_columns: columns)
228
239
  end
229
240
 
230
241
  # Every bin from the first occupied one to the last, stepped from the
231
242
  # first bin so an origin's phase (or label: :right) is kept. A month or a
232
243
  # year cannot be stepped on a finer grid, so it is stepped on the one-month
233
244
  # or one-year grid and then given the bins' unit, as the labels without
234
- # fill: are.
245
+ # keep_empty: are.
235
246
  private def resample_grid(bins, unit)
236
- base = CATime::Resolution.parse(unit).base
237
- if %i[Y M].include?(base)
238
- CArray.time_range(bins.min, bins.max, unit: base, step: unit).to_unit(bins.unit)
247
+ res = CATime::Resolution.parse(unit)
248
+ if %i[Y M].include?(res.base)
249
+ months = res.base == :Y ? res.count * 12 : res.count
250
+ grid = CArray.time_range(bins.min, bins.max, unit: :M, step: "#{months} months")
251
+ # A key coarser than the bins holds one bin for several grid points.
252
+ # key-labels: the bins of a grid, labelled by the caller
253
+ grid.to_unit(bins.unit).unique(sort: true)
254
+ elsif CATime::UnitAlgebra.ratio(res, bins.unit).denominator != 1
255
+ # A step finer than the key is stepped in its own unit; the key holds
256
+ # one bin for several of its points.
257
+ grid = CArray.time_range(bins.min, bins.max, unit: res.base, step: unit)
258
+ # key-labels: the bins of a grid, labelled by the caller
259
+ grid.to_unit(bins.unit).unique(sort: true)
239
260
  else
240
261
  CArray.time_range(bins.min, bins.max, unit: bins.unit, step: unit)
241
262
  end
@@ -286,7 +307,7 @@ class CAFrame
286
307
  end
287
308
 
288
309
  # Each column reduced over all the rows, as a frame of one row: the
289
- # reductions of +GroupedFrame+ with every row in one group. Given names, the
310
+ # reductions of +CAGroupedFrame+ with every row in one group. Given names, the
290
311
  # frame of those columns; without, of every column whose type has the
291
312
  # reduction. A column keeps its type where the reduction keeps it (the
292
313
  # earliest time of a time column is a time), and +min_count:+ /
@@ -329,10 +350,12 @@ class CAFrame
329
350
  # @return [CAFrame] one row: each column's number of distinct present values.
330
351
  # @!method count(*names, keep_rows: false)
331
352
  # @return [CAFrame] one row: each column's number of present values.
332
- # @!method all(*names, keep_rows: false)
333
- # @return [CAFrame] one row, for the boolean columns.
334
- # @!method any(*names, keep_rows: false)
335
- # @return [CAFrame] one row, for the boolean columns.
353
+ # @!method all(*names, keep_rows: false, skip_masked: true)
354
+ # @return [CAFrame] one row, for the boolean columns; +skip_masked:+ as
355
+ # +CArray#all+ takes it.
356
+ # @!method any(*names, keep_rows: false, skip_masked: true)
357
+ # @return [CAFrame] one row, for the boolean columns; +skip_masked:+ as
358
+ # +CArray#any+ takes it.
336
359
  CArray.send(:define_named_methods, self,
337
360
  [:sum, :mean, :min, :max, :prod, :accumulate, :median,
338
361
  :variance, :stddev, :variancep, :stddevp], :reduce_all_rows)
@@ -351,8 +374,9 @@ class CAFrame
351
374
  # a percentile.
352
375
  # @return [CAFrame, CArray] one row; with +keep_rows: true+ the frame's
353
376
  # rows, one name giving the CArray.
354
- def percentile (p, *names, min_count: nil, fill_value: nil, keep_rows: false)
355
- CAFrame.__send__(:check_percentage, p)
377
+ def percentile(p, *names, min_count: nil, fill_value: nil, keep_rows: false)
378
+ keep_rows = CArray.send(:bool_arg, keep_rows, "keep_rows", "percentile")
379
+ p = CAFrame.__send__(:check_percentage, p)
356
380
  reduce_all_rows(:percentile, *names, min_count: min_count, fill_value: fill_value,
357
381
  keep_rows: keep_rows, args: [p])
358
382
  end
@@ -366,17 +390,25 @@ class CAFrame
366
390
  #
367
391
  # @param names [Array<String>] the columns; default every column that has
368
392
  # a quantile.
393
+ # @param min_count [Integer, nil] as for {#percentile}.
394
+ # @param fill_value [Object, Hash, nil] as for {#percentile}.
369
395
  # @return [CAFrame]
370
- def quantile (*names, keep_rows: false)
396
+ def quantile(*names, min_count: nil, fill_value: nil, keep_rows: false)
397
+ keep_rows = CArray.send(:bool_arg, keep_rows, "keep_rows", "quantile")
398
+ walk = ColumnWalk.new(self)
399
+ walk.__send__(:refuse_unknown_fill_columns, :quantile, fill_value)
400
+ walk.__send__(:refuse_wrong_reduction_arguments, :quantile, [], { min_count: min_count }.compact)
371
401
  named = {}
372
- ColumnWalk.new(self).over(:quantile, names) do |col, name|
373
- named[name] = col.quantile(axis: 0, keep_axis: true).map do |q|
402
+ walk.over(:quantile, names) do |col, name|
403
+ fill = fill_value.is_a?(Hash) ? fill_value[name] : fill_value
404
+ kw = { min_count: min_count, fill_value: fill }.compact
405
+ named[name] = col.quantile(axis: 0, keep_axis: true, **kw).map do |q|
374
406
  keep_rows ? q[CArray.int64(@nrow).fill(0), *([nil] * (q.ndim - 1))].copy : q
375
407
  end
376
408
  end
377
409
  cols = CAFrame.__send__(:quantile_columns, named)
378
410
  return CAFrame.new(cols) unless keep_rows
379
- return CAFrame.new(cols, axis_name: @axis_name, index: @index)
411
+ return CAFrame.new(cols, axis_name: @axis_name, index: @index&.copy)
380
412
  end
381
413
 
382
414
  # The five columns a quantile gives a column, by name.
@@ -390,22 +422,20 @@ class CAFrame
390
422
  QUANTILE_SUFFIXES = %w[p0 p25 p50 p75 p100].freeze
391
423
  private_constant :QUANTILE_SUFFIXES
392
424
 
393
- private def reduce_all_rows (reduction, *names, min_count: nil, fill_value: nil, keep_rows: false, args: [])
394
- if fill_value.is_a?(Hash)
395
- unknown = fill_value.keys - column_names
396
- unless unknown.empty?
397
- raise ArgumentError,
398
- "#{reduction}: fill_value names no column #{unknown.map(&:inspect).join(', ')}"
399
- end
400
- end
425
+ private def reduce_all_rows(reduction, *names, min_count: nil, fill_value: nil, keep_rows: false, args: [])
426
+ walk = ColumnWalk.new(self)
427
+ walk.__send__(:refuse_unknown_fill_columns, reduction, fill_value)
428
+ walk.__send__(:refuse_wrong_reduction_arguments, reduction, args,
429
+ { min_count: min_count }.compact)
401
430
  return reduce_down_the_rows(reduction, names, keep_rows, args) do |name|
402
431
  fill = fill_value.is_a?(Hash) ? fill_value[name] : fill_value
403
432
  { min_count: min_count, fill_value: fill }.compact
404
433
  end
405
434
  end
406
435
 
407
- private def reduce_all_rows_to_a_value (reduction, *names, keep_rows: false)
408
- return reduce_down_the_rows(reduction, names, keep_rows) { |_| {} }
436
+ private def reduce_all_rows_to_a_value(reduction, *names, keep_rows: false, **keywords)
437
+ keywords = ColumnWalk.new(self).__send__(:value_reduction_keywords, reduction, keywords)
438
+ return reduce_down_the_rows(reduction, names, keep_rows) { |_| keywords }
409
439
  end
410
440
 
411
441
  # Each named column, or every column whose type has the reduction,
@@ -413,7 +443,7 @@ class CAFrame
413
443
  # it keeps its type as the column's reduction keeps it. The block gives a
414
444
  # column's keywords. A frame of one row with no index; with +keep_rows+,
415
445
  # each row holding the result, as a group's +keep_rows+ gives it.
416
- private def reduce_down_the_rows (reduction, names, keep_rows, args = [])
446
+ private def reduce_down_the_rows(reduction, names, keep_rows, args = [])
417
447
  meth = reduction == :count ? :count_not_masked : reduction
418
448
  named = {}
419
449
  out = ColumnWalk.new(self).over(reduction, names, [], args) do |col, name|
@@ -425,10 +455,10 @@ class CAFrame
425
455
  end
426
456
  return CAFrame.new(named) unless keep_rows
427
457
  return out if out.is_a?(CArray)
428
- return CAFrame.new(named, axis_name: @axis_name, index: @index)
458
+ return CAFrame.new(named, axis_name: @axis_name, index: @index&.copy)
429
459
  end
430
460
 
431
- # Values computed down the rows, one per row, as +GroupedFrame+ computes
461
+ # Values computed down the rows, one per row, as +CAGroupedFrame+ computes
432
462
  # them within each group, with every row in one group: each row's rank
433
463
  # (+order+, int64, 0 the smallest) and the running values up to and
434
464
  # including it. Given names, one name gives the CArray and several a frame
@@ -436,9 +466,9 @@ class CAFrame
436
466
  # the operation. A frame is on the frame's rows and index.
437
467
  #
438
468
  # df["total"] = df.cumsum("rain")
439
- # df["rank"] = df.order("temp", descending: true)
469
+ # df["rank"] = df.rank_index("temp", descending: true)
440
470
  #
441
- # @!method order(*names, descending: false, method: :ordinal, kind: :quick)
471
+ # @!method rank_index(*names, descending: false, method: :ordinal, kind: :quick)
442
472
  # @return [CAFrame, CArray]
443
473
  # @!method cumsum(*names)
444
474
  # @return [CAFrame, CArray]
@@ -451,16 +481,17 @@ class CAFrame
451
481
  # @!method cumcount(*names)
452
482
  # @return [CAFrame, CArray]
453
483
  CArray.send(:define_named_methods, self,
454
- [:order, :cumsum, :cumprod, :cummax, :cummin, :cumcount], :run_down_all_rows)
484
+ [:rank_index, :cumsum, :cumprod, :cummax, :cummin, :cumcount], :run_down_all_rows)
455
485
 
456
- private def run_down_all_rows (operation, *names, **keywords)
486
+ private def run_down_all_rows(operation, *names, **keywords)
457
487
  # The keywords are the core's to check, before any column is read.
458
488
  CArray.float64(1).public_send(operation, **keywords)
459
489
  out = ColumnWalk.new(self).over(operation, names, [], [], keywords) do |col, _|
460
490
  col.public_send(operation, **(col.ndim > 1 ? keywords.merge(axis: 0) : keywords))
461
491
  end
492
+ ColumnWalk.new(self).__send__(:refuse_no_column_on_rows, operation, out, @nrow)
462
493
  return out if out.is_a?(CArray)
463
- return CAFrame.new(out, axis_name: @axis_name, index: @index)
494
+ return CAFrame.new(out, axis_name: @axis_name, index: @index&.copy)
464
495
  end
465
496
 
466
497
  # The frame's own walk over its columns: the one rule of a frame-wide verb
@@ -469,11 +500,11 @@ class CAFrame
469
500
  class ColumnWalk
470
501
  include CAFrame::ColumnVerbs
471
502
 
472
- def initialize (frame)
503
+ def initialize(frame)
473
504
  @frame = frame
474
505
  end
475
506
 
476
- def over (verb, names, key_names = [], args = [], keywords = {}, &block)
507
+ def over(verb, names, key_names = [], args = [], keywords = {}, &block)
477
508
  return over_named_columns(verb, names, key_names, args, keywords, &block)
478
509
  end
479
510
  end
@@ -493,7 +524,7 @@ class CAFrame
493
524
  # df["dtemp"] = df["temp"] - df.lag("temp", before: "1 hour")
494
525
  # df.lag("temp", n: 1) # the previous row
495
526
  #
496
- # +GroupedFrame#lag+ does the same within each group. Given names, one
527
+ # +CAGroupedFrame#lag+ does the same within each group. Given names, one
497
528
  # name gives the CArray and several a frame of those columns; without
498
529
  # names, a frame of every column (the +on:+ column left out). A frame is
499
530
  # on the frame's rows and index. A result shows the column's attributes, as +CArray#lag+'s
@@ -509,11 +540,13 @@ class CAFrame
509
540
  # @raise [ArgumentError] when +n:+, +before:+ and +after:+ are combined,
510
541
  # when +on:+ comes without a distance, when there is no key, or when the
511
542
  # key repeats (the row at a key would not be one row).
512
- def lag (*names, n: nil, before: nil, after: nil, on: nil)
543
+ def lag(*names, n: nil, before: nil, after: nil, on: nil)
513
544
  distance = lag_distance("lag", n, before, after, on)
514
545
  walk = ColumnWalk.new(self)
515
546
  if distance.nil?
516
547
  step = n.nil? ? 1 : n
548
+ # A wrong n: would otherwise read as no column having a lag.
549
+ CArray.float64(1).lag(step)
517
550
  cols = walk.over(:lag, names, [], [step]) do |col, _|
518
551
  (col.ndim > 1 ? col.lag(step, axis: 0) : col.lag(step)).copy
519
552
  end
@@ -524,11 +557,11 @@ class CAFrame
524
557
  end
525
558
  end
526
559
  return cols if cols.is_a?(CArray)
527
- CAFrame.new(cols, axis_name: @axis_name, index: @index)
560
+ CAFrame.new(cols, axis_name: @axis_name, index: @index&.copy)
528
561
  end
529
562
 
530
563
  # [key name, key, sign, width] for a lag by distance; nil for one by rows.
531
- private def lag_distance (verb, n, before, after, on)
564
+ private def lag_distance(verb, n, before, after, on)
532
565
  if before.nil? && after.nil?
533
566
  raise ArgumentError, "#{verb}: on: goes with before: or after:" unless on.nil?
534
567
  return nil
@@ -548,7 +581,7 @@ class CAFrame
548
581
  on_name = column_key(on, verb)
549
582
  end
550
583
  key = key_column(on_name, verb)
551
- unless key.is_a?(CATime) || key.is_a?(CATimedelta) || (!key.face? && key.numeric?)
584
+ unless key.is_a?(CATime) || key.is_a?(CATimedelta) || (!key.face? && key.numeric? && !key.complex?)
552
585
  raise ArgumentError,
553
586
  "#{verb}: the key #{on_name.inspect} is #{CArray::Inspector.type_label(key)}; " \
554
587
  "a distance is taken along a time, a duration or a number"
@@ -562,7 +595,7 @@ class CAFrame
562
595
  # key moved by the width; masked where there is none. A row in no set is
563
596
  # masked too, and so is a row whose key is NaN or infinite, which is no
564
597
  # distance from any key (as in windows).
565
- private def lag_addresses (verb, row_sets, _on_name, key, sign, width)
598
+ private def lag_addresses(verb, row_sets, _on_name, key, sign, width)
566
599
  key = key.mask_invalid if key.float?
567
600
  addr = CArray.int64(nrow)
568
601
  addr[] = UNDEF
@@ -581,10 +614,10 @@ class CAFrame
581
614
 
582
615
  # The keys moved by the width. A time is moved on the finer of its unit and
583
616
  # the width's, so that an hour back from a day is not rounded onto the day.
584
- private def lag_target (keys, sign, width)
617
+ private def lag_target(keys, sign, width)
585
618
  if width.is_a?(CATimedelta::Element) &&
586
- CATimeUnitAlgebra.same_group?(keys.unit.base, width.unit.base)
587
- keys = keys.to_unit(CATimeUnitAlgebra.finer(keys.unit, width.unit))
619
+ CATime::UnitAlgebra.same_group?(keys.unit.base, width.unit.base)
620
+ keys = keys.to_unit(CATime::UnitAlgebra.finer(keys.unit, width.unit))
588
621
  end
589
622
  return lag_integer_target(keys, sign, width) if keys.integer?
590
623
  return keys.public_send(sign, width)
@@ -597,7 +630,7 @@ class CAFrame
597
630
  # for a 64-bit key a step does not fit in). A target outside the key's
598
631
  # range is masked, so it matches no row rather than wrapping onto one; a
599
632
  # width that is not a whole number matches no row either.
600
- private def lag_integer_target (keys, sign, width)
633
+ private def lag_integer_target(keys, sign, width)
601
634
  bits = keys.bytes * 8
602
635
  if LAG_UNSIGNED.include?(keys.data_type)
603
636
  lo, hi = 0, 2**bits - 1
@@ -628,7 +661,7 @@ class CAFrame
628
661
 
629
662
  end
630
663
 
631
- # GroupedFrame — the result of +CAFrame#group_by+ (memo §11.6, §16).
664
+ # CAGroupedFrame — the result of +CAFrame#group_by+ (memo §11.6, §16).
632
665
  #
633
666
  # Holds the grouping categorical once (grouping is per-key, computed once
634
667
  # and shared across every column). The surfaces:
@@ -636,7 +669,7 @@ end
636
669
  # aggregate(spec) -> declarative per-column reductions into a new frame
637
670
  # aggregate { |grp| } -> columns built from iterators, run once
638
671
  # table { |g| } -> Ruby escape, g is a per-group view-frame
639
- class GroupedFrame
672
+ class CAGroupedFrame
640
673
  include CAFrame::ColumnVerbs
641
674
  # +key_names+ are the frame columns the grouping was keyed on. They become
642
675
  # the result's index, so the reduction shortcuts must not also return them as
@@ -651,7 +684,7 @@ class GroupedFrame
651
684
  # key, one value per row) become its first columns, each holding the key's
652
685
  # value at each group's first row; +label_columns:+ (name => one value per
653
686
  # group, in code order) give them directly, for groups that may have no
654
- # rows (resample with fill: true).
687
+ # rows (resample with keep_empty: true).
655
688
  #
656
689
  # The grouping and the index are taken here, so a later change to the key
657
690
  # does not rename the groups; the values are read when a reduction is.
@@ -669,24 +702,24 @@ class GroupedFrame
669
702
  end
670
703
 
671
704
  # Number of groups.
672
- def ngroup
705
+ def ngroups
673
706
  @labels.size
674
707
  end
675
708
 
676
709
  # The number of rows in each group, as a frame of one column, "size"
677
710
  # unless +name:+ says otherwise, labelled as a reduction's result is. A row
678
- # whose key is masked is in no group, so the sizes need not add up to the
679
- # frame's nrow.
711
+ # counts whatever its values are, masked or not; a row whose key is masked
712
+ # is in no group, so the sizes need not add up to the frame's nrow.
680
713
  #
681
714
  # @param name [String] the result column's name.
682
715
  # @return [CAFrame]
683
716
  # @raise [ArgumentError] when a key has that name.
684
- def size (name: "size")
685
- refuse_changed_rows("size")
686
- name = @frame.__send__(:column_name_arg, name, "size")
717
+ def group_sizes(name: "size")
718
+ refuse_changed_rows("group_sizes")
719
+ name = @frame.__send__(:column_name_arg, name, "group_sizes")
687
720
  if @key_names.include?(name) || @axis_name == name
688
721
  raise ArgumentError,
689
- "size: a key is named #{name.inspect}; name the result otherwise, as in size(name: \"n\")"
722
+ "group_sizes: a key is named #{name.inspect}; name the result otherwise, as in group_sizes(name: \"n\")"
690
723
  end
691
724
  return result_frame({ name => @cat.category_sizes.int64 }, false)
692
725
  end
@@ -699,11 +732,11 @@ class GroupedFrame
699
732
  #
700
733
  # @yieldparam label [Object, Array] the group's key value(s).
701
734
  # @yieldparam rows [CAFrame] the group's rows.
702
- # @return [GroupedFrame] self
735
+ # @return [CAGroupedFrame] self
703
736
  def each
704
- return enum_for(:each) { ngroup } unless block_given?
737
+ return enum_for(:each) { ngroups } unless block_given?
705
738
  refuse_changed_rows("each")
706
- ngroup.times { |k| yield @labels[k], @frame[group_address(k)] }
739
+ ngroups.times { |k| yield @labels[k], @frame[group_address(k)] }
707
740
  return self
708
741
  end
709
742
 
@@ -782,6 +815,7 @@ class GroupedFrame
782
815
  # @raise [ArgumentError] when both a spec and a block are given, or the
783
816
  # block returns something other than a Hash of per-group CArrays.
784
817
  def aggregate(spec = nil, keep_rows: false, **named, &block)
818
+ keep_rows = CArray.send(:bool_arg, keep_rows, "keep_rows", "aggregate")
785
819
  refuse_changed_rows("aggregate")
786
820
  if block
787
821
  unless spec.nil? && named.empty?
@@ -804,7 +838,7 @@ class GroupedFrame
804
838
  cols[out] =
805
839
  case reduction
806
840
  when Symbol
807
- group_reduce(@frame[in_name], reduction, *args, **options)
841
+ group_reduce(@frame.__send__(:named_column, in_name, "aggregate"), reduction, *args, **options)
808
842
  when Proc
809
843
  unless args.empty? && options.empty?
810
844
  raise ArgumentError, "aggregate: a Proc reduction takes no arguments (#{out.inspect})"
@@ -827,6 +861,8 @@ class GroupedFrame
827
861
  # first appear; a group whose Hash lacks a name is UNDEF there, as
828
862
  # +from_records+ reads a record that lacks a key.
829
863
  def table(keep_rows: false)
864
+ keep_rows = CArray.send(:bool_arg, keep_rows, "keep_rows", "table")
865
+ raise ArgumentError, "table: give a block" unless block_given?
830
866
  refuse_changed_rows("table")
831
867
  outs = []
832
868
  each_group_frame do |g|
@@ -914,7 +950,7 @@ class GroupedFrame
914
950
  [:sum, :mean, :min, :max, :prod, :accumulate, :median,
915
951
  :variance, :stddev, :variancep, :stddevp], :group_reduction)
916
952
 
917
- private def group_reduction (red, *names, min_count: nil, fill_value: nil, keep_rows: false)
953
+ private def group_reduction(red, *names, min_count: nil, fill_value: nil, keep_rows: false)
918
954
  refuse_changed_rows(red)
919
955
  reduce_columns(red, names, keep_rows, min_count: min_count, fill_value: fill_value)
920
956
  end
@@ -928,8 +964,9 @@ class GroupedFrame
928
964
  # @param names [Array<String>] the columns; default every column that has
929
965
  # a percentile.
930
966
  # @return [CAFrame, CArray] one row per group, as {#sum} returns.
931
- def percentile (p, *names, min_count: nil, fill_value: nil, keep_rows: false)
932
- CAFrame.__send__(:check_percentage, p)
967
+ def percentile(p, *names, min_count: nil, fill_value: nil, keep_rows: false)
968
+ keep_rows = CArray.send(:bool_arg, keep_rows, "keep_rows", "percentile")
969
+ p = CAFrame.__send__(:check_percentage, p)
933
970
  refuse_changed_rows(:percentile)
934
971
  reduce_columns(:percentile, names, keep_rows, args: [p], min_count: min_count, fill_value: fill_value)
935
972
  end
@@ -943,17 +980,24 @@ class GroupedFrame
943
980
  #
944
981
  # @param names [Array<String>] the columns; default every column that has
945
982
  # a quantile.
983
+ # @param min_count [Integer, nil] as for {#percentile}.
984
+ # @param fill_value [Object, Hash, nil] as for {#percentile}.
946
985
  # @return [CAFrame]
947
- def quantile (*names, keep_rows: false)
986
+ def quantile(*names, min_count: nil, fill_value: nil, keep_rows: false)
987
+ keep_rows = CArray.send(:bool_arg, keep_rows, "keep_rows", "quantile")
948
988
  refuse_changed_rows(:quantile)
949
989
  refuse_key_as_result(:quantile, names) unless keep_rows
990
+ refuse_unknown_fill_columns(:quantile, fill_value)
991
+ refuse_wrong_reduction_arguments(:quantile, [], { min_count: min_count }.compact)
950
992
  named = {}
951
993
  over_named_columns(:quantile, names, @key_names) do |col, name|
952
- named[name] = group_reduce(col, :quantile).map { |q| keep_rows ? spread_to_rows(q) : q }
994
+ fill = fill_value.is_a?(Hash) ? fill_value[name] : fill_value
995
+ kw = { min_count: min_count, fill_value: fill }.compact
996
+ named[name] = group_reduce(col, :quantile, **kw).map { |q| keep_rows ? spread_to_rows(q) : q }
953
997
  end
954
998
  cols = CAFrame.__send__(:quantile_columns, named)
955
999
  return result_frame(cols, false) unless keep_rows
956
- return CAFrame.new(cols, axis_name: @frame.axis_name, index: @frame.index)
1000
+ return CAFrame.new(cols, axis_name: @frame.axis_name, index: @frame.index&.copy)
957
1001
  end
958
1002
 
959
1003
  # The same convenience for the reductions that take no min_count: or
@@ -974,20 +1018,22 @@ class GroupedFrame
974
1018
  # Returns each group's number of present values (int64), a masked cell
975
1019
  # left out.
976
1020
  # @return [CAFrame] one row per group.
977
- # @!method all(*names, keep_rows: false)
1021
+ # @!method all(*names, keep_rows: false, skip_masked: true)
978
1022
  # Returns whether every present value of the group is true, for the
979
- # boolean columns.
1023
+ # boolean columns. With +skip_masked: false+ a group is UNDEF when a
1024
+ # masked cell could change it, as +CArray#all+ folds it.
980
1025
  # @return [CAFrame] one row per group.
981
- # @!method any(*names, keep_rows: false)
1026
+ # @!method any(*names, keep_rows: false, skip_masked: true)
982
1027
  # Returns whether any present value of the group is true, for the
983
- # boolean columns.
1028
+ # boolean columns; +skip_masked:+ as for +all+.
984
1029
  # @return [CAFrame] one row per group.
985
1030
  CArray.send(:define_named_methods, self,
986
1031
  [:first, :last, :nunique, :count, :all, :any], :group_value)
987
1032
 
988
- private def group_value (red, *names, keep_rows: false)
1033
+ private def group_value(red, *names, keep_rows: false, **keywords)
1034
+ keywords = value_reduction_keywords(red, keywords)
989
1035
  refuse_changed_rows(red)
990
- reduce_columns(red, names, keep_rows)
1036
+ reduce_columns(red, names, keep_rows, **keywords)
991
1037
  end
992
1038
 
993
1039
  # Values computed within each group and kept on the frame's rows, in row
@@ -999,7 +1045,7 @@ class GroupedFrame
999
1045
  # columns (several) on the frame's rows and index. An N-D column runs along the rows.
1000
1046
  #
1001
1047
  # df["dtemp"] = df["temp"] - grp.lag("temp") # change since the station's previous row
1002
- # grp.order("temp", descending: true) # rank within the station
1048
+ # grp.rank_index("temp", descending: true) # rank within the station
1003
1049
  # grp.cumsum("rain") # running total per station
1004
1050
  #
1005
1051
  # "Previous" is the previous row of the frame: sort the frame first
@@ -1012,9 +1058,9 @@ class GroupedFrame
1012
1058
  # (the index, or the column +on:+ names) is that distance earlier (or
1013
1059
  # later), as +CAFrame#lag+ gives it.
1014
1060
  # @return [CAFrame, CArray]
1015
- # @!method order(*names, descending: false, method: :ordinal, kind: :quick)
1061
+ # @!method rank_index(*names, descending: false, method: :ordinal, kind: :quick)
1016
1062
  # Returns each row's rank among its group's rows (int64, 0 the
1017
- # smallest), as +CArray#order+ ranks them.
1063
+ # smallest), as +CArray#rank_index+ ranks them.
1018
1064
  # @return [CAFrame, CArray]
1019
1065
  # @!method cumsum(*names)
1020
1066
  # Returns the running sum within each group, as +CArray#cumsum+.
@@ -1031,100 +1077,104 @@ class GroupedFrame
1031
1077
  # @!method cumcount(*names)
1032
1078
  # Returns the running count of present values within each group (int64).
1033
1079
  # @return [CAFrame, CArray]
1034
- def lag (*names, n: nil, before: nil, after: nil, on: nil)
1080
+ def lag(*names, n: nil, before: nil, after: nil, on: nil)
1035
1081
  distance = @frame.__send__(:lag_distance, "lag", n, before, after, on)
1036
1082
  return transform_columns(:lag, names, [n.nil? ? 1 : n], {}) if distance.nil?
1037
1083
  refuse_changed_rows("lag")
1038
1084
  refuse_key_on_rows(:lag, names)
1039
- addr = @frame.__send__(:lag_addresses, "lag", (0...ngroup).map { |k| group_address(k) }, *distance)
1085
+ addr = @frame.__send__(:lag_addresses, "lag", (0...ngroups).map { |k| group_address(k) }, *distance)
1040
1086
  out = over_named_columns(:lag, names, @key_names | [distance.first], [1], {}) do |col|
1041
1087
  col[addr, *([nil] * (col.ndim - 1))].copy
1042
1088
  end
1043
1089
  return out if out.is_a?(CArray)
1044
- CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index)
1090
+ CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index&.copy)
1045
1091
  end
1046
1092
 
1047
- def order (*names, descending: false, method: :ordinal, kind: :quick)
1048
- transform_columns(:order, names, [], { descending: descending, method: method, kind: kind })
1093
+ def rank_index(*names, descending: false, method: :ordinal, kind: :quick)
1094
+ descending = CArray.send(:bool_arg, descending, "descending", "rank_index")
1095
+ transform_columns(:rank_index, names, [], { descending: descending, method: method, kind: kind })
1049
1096
  end
1050
1097
 
1051
1098
  CArray.send(:define_named_methods, self,
1052
1099
  [:cumsum, :cumprod, :cummax, :cummin, :cumcount], :group_scan)
1053
1100
 
1054
- private def group_scan (op, *names)
1101
+ private def group_scan(op, *names)
1055
1102
  transform_columns(op, names, [], {})
1056
1103
  end
1057
1104
 
1058
1105
  # Fill the masked cells of a column from the rows of the same group, in
1059
- # place, as +CAFrame#fill+ does for the whole column: +:ffill+ carries the
1060
- # group's last present value forward in row order, +:bfill+ its next one
1106
+ # place, as +CAFrame#unmask+ does for the whole column: +:forward+ carries the
1107
+ # group's last present value forward in row order, +:backward+ its next one
1061
1108
  # back, and +:linear+ interpolates between the group's present values
1062
1109
  # against the frame's index (against the row position within the group
1063
1110
  # when the frame has no index). A fill never reaches across into another
1064
1111
  # group, so a cell with nothing to carry or interpolate from in its group
1065
1112
  # stays masked, and a row whose key is masked (in no group) is left as it
1066
- # is. A constant fills every masked cell, as +CAFrame#fill+ does. Returns
1113
+ # is. A constant fills every masked cell, as +CAFrame#unmask+ does. Returns
1067
1114
  # self.
1068
1115
  #
1069
- # df.group_by("station").fill("temp", :ffill)
1070
- # df.group_by("station").fill("temp", :linear)
1071
- # df.group_by("station").fill("temp" => :linear, "rain" => 0.0)
1072
- # df.group_by("station").fill("temp", "rain", :linear)
1073
- # df.group_by("station").fill(:ffill) # every column with a masked cell
1116
+ # df.group_by("station").unmask("temp", method: :forward)
1117
+ # df.group_by("station").unmask("temp", method: :linear)
1118
+ # df.group_by("station").unmask(method: { "temp" => :linear, "rain" => :forward })
1119
+ # df.group_by("station").unmask("temp", "rain", method: :linear)
1120
+ # df.group_by("station").unmask(method: :forward) # every column with a masked cell
1121
+ # df.group_by("station").unmask("rain", 0.0)
1074
1122
  #
1075
- # +:ffill+ and +:bfill+ follow the row order: sort the frame first
1123
+ # +:forward+ and +:backward+ follow the row order: sort the frame first
1076
1124
  # (+sort_by_key("time")+) when its rows are not in time order. +:linear+
1077
- # reads each group in the order of the index, as +CAFrame#fill+ does.
1078
- #
1079
- # @param args [Array] the columns, as +CAFrame#fill+ takes them, then
1080
- # +:ffill+, +:bfill+, +:linear+, or a constant; or one Hash of them.
1081
- # @return [GroupedFrame] self
1082
- # @raise [ArgumentError] for another Symbol, or for +:linear+ on a column
1083
- # or index +CAFrame#fill+ cannot interpolate.
1084
- def fill (*args)
1085
- plan = @frame.__send__(:fill_arguments, args, @key_names)
1125
+ # reads each group in the order of the index, as +CAFrame#unmask+ does.
1126
+ #
1127
+ # @param args [Array] the columns, as +CAFrame#unmask+ takes them, then a
1128
+ # constant (a Symbol is a constant); or one Hash of constants.
1129
+ # @param method [Symbol, Hash, nil] +:forward+, +:backward+ or +:linear+,
1130
+ # or a Hash of them by column.
1131
+ # @return [CAGroupedFrame] self
1132
+ # @raise [ArgumentError] for another method, or for +:linear+ on a column
1133
+ # or index +CAFrame#unmask+ cannot interpolate.
1134
+ def unmask(*args, method: nil, **named)
1135
+ plan = @frame.__send__(:fill_arguments, args, named, method, @key_names)
1086
1136
  return self if plan.nil?
1087
1137
  refuse_key_on_rows(:fill, plan.is_a?(Hash) ? plan.keys : [plan.first])
1088
1138
  if plan.is_a?(Hash)
1089
- @frame.__send__(:fill_by_map, plan, "fill") do |frame, key, how|
1139
+ @frame.__send__(:fill_by_map, plan, "unmask") do |frame, key, how|
1090
1140
  grouped = if frame.equal?(@frame)
1091
1141
  self
1092
1142
  else
1093
1143
  # key-labels: the groups' index as it is, on a copy of the frame
1094
- GroupedFrame.new(frame, @cat, @axis_name, @key_names, index: @index,
1144
+ CAGroupedFrame.new(frame, @cat, @axis_name, @key_names, index: @index,
1095
1145
  label_columns: @label_columns)
1096
1146
  end
1097
- grouped.fill(key, how)
1147
+ grouped.__send__(:unmask_column, key, how)
1098
1148
  end
1099
1149
  return self
1100
1150
  end
1101
- name, method_or_value = plan
1102
- refuse_changed_rows("fill")
1103
- case method_or_value
1104
- when :ffill, :bfill
1151
+ unmask_column(*plan)
1152
+ end
1153
+
1154
+ private def unmask_column(name, how)
1155
+ refuse_changed_rows("unmask")
1156
+ unless how.is_a?(CAFrame.const_get(:FillMethod))
1157
+ @frame.unmask(name, how)
1158
+ return self
1159
+ end
1160
+ case how.name
1161
+ when :forward, :backward
1105
1162
  @frame.__send__(:refuse_if_frozen)
1106
- key = @frame.__send__(:column_key, name, "fill")
1107
- col = @frame[key]
1163
+ key = @frame.__send__(:column_key, name, "unmask")
1164
+ col = @frame.__send__(:named_column, key, "unmask")
1108
1165
  # A row in no group is UNDEF in the fill, so writing it changes nothing.
1109
- held = group_transform(col, :strip_mask, [], { method: method_or_value })
1110
- target = col.is_masked
1111
- col[target] = held[target] if target.any
1166
+ held = group_transform(col, :strip_mask, [], { method: how.name })
1167
+ @frame.__send__(:write_filled_cells, col, held)
1112
1168
  when :linear
1113
1169
  @frame.__send__(:refuse_if_frozen)
1114
- key = @frame.__send__(:column_key, name, "fill")
1115
- # The column and the index are checked as CAFrame#fill checks them,
1170
+ key = @frame.__send__(:column_key, name, "unmask")
1171
+ # The column and the index are checked as CAFrame#unmask checks them,
1116
1172
  # on no rows, so a call without groups is refused as one with groups.
1117
- @frame.__send__(:select_rows, CA_INT64([])).fill(key, :linear)
1173
+ @frame.__send__(:select_rows, CA_INT64([])).unmask(key, method: :linear)
1118
1174
  # Each group's rows as a frame of views, so its fill writes through.
1119
- ngroup.times do |k|
1120
- @frame.__send__(:select_rows, group_address(k)).fill(key, :linear)
1175
+ ngroups.times do |k|
1176
+ @frame.__send__(:select_rows, group_address(k)).unmask(key, method: :linear)
1121
1177
  end
1122
- when Symbol
1123
- raise ArgumentError,
1124
- "fill: unknown method #{method_or_value.inspect} " \
1125
- "(:ffill | :bfill, or a constant fill value)"
1126
- else
1127
- @frame.fill(name, method_or_value)
1128
1178
  end
1129
1179
  self
1130
1180
  end
@@ -1138,7 +1188,7 @@ class GroupedFrame
1138
1188
  #
1139
1189
  # @param n [Integer] how many rows per group, 0 or more (default 5).
1140
1190
  # @return [CAFrame]
1141
- def head (n = 5)
1191
+ def head(n = 5)
1142
1192
  return rows_at_the_ends_of_groups("head", n) { |addr| addr.first(n) }
1143
1193
  end
1144
1194
 
@@ -1146,17 +1196,17 @@ class GroupedFrame
1146
1196
  #
1147
1197
  # @param n [Integer] how many rows per group, 0 or more (default 5).
1148
1198
  # @return [CAFrame]
1149
- def tail (n = 5)
1199
+ def tail(n = 5)
1150
1200
  return rows_at_the_ends_of_groups("tail", n) { |addr| addr.last(n) }
1151
1201
  end
1152
1202
 
1153
- private def rows_at_the_ends_of_groups (verb, n)
1203
+ private def rows_at_the_ends_of_groups(verb, n)
1154
1204
  refuse_changed_rows(verb)
1155
1205
  unless n.is_a?(Integer)
1156
1206
  raise TypeError, "#{verb}: the count is an Integer (got #{n.inspect})"
1157
1207
  end
1158
1208
  raise ArgumentError, "#{verb}: the count must be 0 or more (got #{n})" if n < 0
1159
- picked = (0...ngroup).flat_map { |k| yield(group_address(k).to_a) }.sort
1209
+ picked = (0...ngroups).flat_map { |k| yield(group_address(k).to_a) }.sort
1160
1210
  return @frame[CA_INT64(picked)]
1161
1211
  end
1162
1212
 
@@ -1173,7 +1223,7 @@ class GroupedFrame
1173
1223
  # @param keys [Array<String>] the key columns (or the index axis name).
1174
1224
  # @return [CAFrame]
1175
1225
  # @raise [ArgumentError] when +n+ is negative or no key is given.
1176
- def nlargest (n, *keys)
1226
+ def nlargest(n, *keys)
1177
1227
  return largest_rows_of_groups("nlargest", n, keys, true)
1178
1228
  end
1179
1229
 
@@ -1184,11 +1234,11 @@ class GroupedFrame
1184
1234
  # @param keys [Array<String>] the key columns (or the index axis name).
1185
1235
  # @return [CAFrame]
1186
1236
  # @raise [ArgumentError] when +n+ is negative or no key is given.
1187
- def nsmallest (n, *keys)
1237
+ def nsmallest(n, *keys)
1188
1238
  return largest_rows_of_groups("nsmallest", n, keys, false)
1189
1239
  end
1190
1240
 
1191
- private def largest_rows_of_groups (verb, n, keys, descending)
1241
+ private def largest_rows_of_groups(verb, n, keys, descending)
1192
1242
  refuse_changed_rows(verb)
1193
1243
  unless n.is_a?(Integer)
1194
1244
  raise TypeError, "#{verb}: the count is an Integer (got #{n.inspect})"
@@ -1198,7 +1248,7 @@ class GroupedFrame
1198
1248
  cols = keys.map do |key|
1199
1249
  @frame.__send__(:key_column, @frame.__send__(:column_key, key, verb), verb)
1200
1250
  end
1201
- sort_keys = cols.map { |col| descending ? col.order(descending: true, method: :dense) : col }
1251
+ sort_keys = cols.map { |col| descending ? col.rank_index(descending: true, method: :dense) : col }
1202
1252
  # Rows sorted by group, then by the keys; a row in no group comes last.
1203
1253
  addr = CArray.sort_addr(group_codes, *sort_keys, masked_position: :last).to_a
1204
1254
  picked = []
@@ -1223,13 +1273,14 @@ class GroupedFrame
1223
1273
  # undetermined, as is a row whose key is masked (it belongs to no group):
1224
1274
  # such rows are not kept, as +CAFrame#filter+ does not keep them.
1225
1275
  #
1226
- # @yieldparam grouped [GroupedFrame] self.
1276
+ # @yieldparam grouped [CAGroupedFrame] self.
1227
1277
  # @yieldreturn [CArray] boolean, one value per group.
1228
1278
  # @return [CAFrame]
1229
1279
  # @raise [ArgumentError] when the block does not return a boolean CArray of
1230
- # shape [ngroup].
1231
- def filter (**options)
1280
+ # shape [ngroups].
1281
+ def filter(**options)
1232
1282
  CAFrame.__send__(:refuse_filter_keywords, options, "filter")
1283
+ raise ArgumentError, "filter: give a block" unless block_given?
1233
1284
  refuse_changed_rows("filter")
1234
1285
  chosen = yield(self)
1235
1286
  unless chosen.is_a?(CArray) && chosen.data_type == :boolean
@@ -1237,10 +1288,10 @@ class GroupedFrame
1237
1288
  "filter block must return a boolean CArray (got #{chosen.is_a?(CArray) ? "a #{CArray::Inspector.type_label(chosen)} CArray" : chosen.class})" +
1238
1289
  CAFrame.__send__(:equality_hint, chosen)
1239
1290
  end
1240
- unless chosen.shape == [ngroup]
1291
+ unless chosen.shape == [ngroups]
1241
1292
  raise ArgumentError,
1242
1293
  "filter mask has shape #{chosen.shape.inspect}, " \
1243
- "expected [#{ngroup}] (one value per group)"
1294
+ "expected [#{ngroups}] (one value per group)"
1244
1295
  end
1245
1296
  rows = spread_to_rows(chosen)
1246
1297
  @frame.filter(rows)
@@ -1251,7 +1302,7 @@ class GroupedFrame
1251
1302
  # Nothing is copied, so a write to a cell reaches the grouped frame's
1252
1303
  # rows; adding or dropping a column changes the new frame only.
1253
1304
  #
1254
- # def warm_stations (grp)
1305
+ # def warm_stations(grp)
1255
1306
  # grp.filter { |g| g["temp"].mean > 15.0 } # the rows of some groups
1256
1307
  # end
1257
1308
  # grp.to_frame # all of its rows
@@ -1264,7 +1315,7 @@ class GroupedFrame
1264
1315
 
1265
1316
  # @return [String]
1266
1317
  def inspect
1267
- "#<GroupedFrame ngroup=#{ngroup} by=#{@axis_name.inspect}>"
1318
+ "#<CAGroupedFrame ngroups=#{ngroups} by=#{@axis_name.inspect}>"
1268
1319
  end
1269
1320
 
1270
1321
  # A within-group transform of the named columns, or of every column whose
@@ -1278,17 +1329,27 @@ class GroupedFrame
1278
1329
  out = over_named_columns(op, names, @key_names, args, keywords) do |col|
1279
1330
  group_transform(col, op, args, keywords)
1280
1331
  end
1332
+ refuse_no_column_on_rows(op, out, @frame.nrow)
1281
1333
  return out if out.is_a?(CArray)
1282
- CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index)
1334
+ CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index&.copy)
1283
1335
  end
1284
1336
 
1285
1337
  # A column's within-group transform: an N-D column runs along the rows.
1286
1338
  private def group_transform(col, op, args, keywords)
1339
+ return group_lag_by_rows(col, *args) if op == :lag && col.face? && !col.__send__(:holds_new_values?)
1287
1340
  it = col.group_by_category(@cat)
1288
1341
  keywords = keywords.merge(axis: 0) if col.ndim > 1
1289
1342
  it.public_send(op, *args, **keywords)
1290
1343
  end
1291
1344
 
1345
+ # A Face that cannot hold new values answers an iterator's lag in object
1346
+ # cells. Reading each cell from the row it lags keeps the Face, as
1347
+ # lag(before:) does.
1348
+ private def group_lag_by_rows(col, step)
1349
+ rows = CArray.int64(@frame.nrow).seq.group_by_category(@cat).lag(step)
1350
+ col[rows, *([nil] * (col.ndim - 1))].copy
1351
+ end
1352
+
1292
1353
  # Each result gets its own index.
1293
1354
  private def label_index
1294
1355
  return @index.copy if @index
@@ -1302,13 +1363,8 @@ class GroupedFrame
1302
1363
  refuse_key_as_result(reduction, names) unless keep_rows
1303
1364
  keywords = keywords.compact
1304
1365
  fills = keywords.delete(:fill_value)
1305
- if fills.is_a?(Hash)
1306
- unknown = fills.keys - @frame.column_names
1307
- unless unknown.empty?
1308
- raise ArgumentError,
1309
- "#{reduction}: fill_value names no column #{unknown.map(&:inspect).join(', ')}"
1310
- end
1311
- end
1366
+ refuse_unknown_fill_columns(reduction, fills)
1367
+ refuse_wrong_reduction_arguments(reduction, args, keywords)
1312
1368
  named = {}
1313
1369
  out = over_named_columns(reduction, names, @key_names, args) do |col, name|
1314
1370
  fill = fills.is_a?(Hash) ? fills[name] : fills
@@ -1322,7 +1378,7 @@ class GroupedFrame
1322
1378
  # labels beside it.
1323
1379
  if keep_rows
1324
1380
  return out if out.is_a?(CArray)
1325
- return CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index)
1381
+ return CAFrame.new(out, axis_name: @frame.axis_name, index: @frame.index&.copy)
1326
1382
  end
1327
1383
  result_frame(named, false)
1328
1384
  end
@@ -1332,7 +1388,7 @@ class GroupedFrame
1332
1388
  private def refuse_key_as_result(reduction, names)
1333
1389
  named = names.map { |n| n.is_a?(String) ? n : nil }.compact & @key_names
1334
1390
  return if named.empty?
1335
- hint = reduction == :count ? "; the number of rows of each group is size" : ""
1391
+ hint = reduction == :count ? "; the number of rows of each group is group_sizes" : ""
1336
1392
  raise ArgumentError,
1337
1393
  "#{reduction}: #{named.first.inspect} is the group key, already in the result#{hint}"
1338
1394
  end
@@ -1360,7 +1416,7 @@ class GroupedFrame
1360
1416
  return CAFrame.new(@label_columns.transform_values(&:copy).merge(cols))
1361
1417
  end
1362
1418
  CAFrame.new(cols.transform_values { |col| spread_to_rows(col) },
1363
- axis_name: @frame.axis_name, index: @frame.index)
1419
+ axis_name: @frame.axis_name, index: @frame.index&.copy)
1364
1420
  end
1365
1421
 
1366
1422
  # A per-group result (one entry per group along axis 0) laid back over the
@@ -1377,6 +1433,10 @@ class GroupedFrame
1377
1433
  # A column's group reduction. An N-D column is reduced along the rows, so
1378
1434
  # each group keeps the trailing shape: a profile column (N, L) gives (G, L).
1379
1435
  private def group_reduce(col, reduction, *args, **keywords)
1436
+ if %i[first last].include?(reduction) && col.ndim == 1 && args.empty? && keywords.empty? &&
1437
+ col.face? && !col.__send__(:holds_new_values?)
1438
+ return col[present_rows(col).group_by_category(@cat).public_send(reduction)].copy
1439
+ end
1380
1440
  it = col.group_by_category(@cat)
1381
1441
  if col.ndim > 1 && !keywords.key?(:axis)
1382
1442
  it.public_send(reduction, *args, axis: 0, **keywords)
@@ -1393,11 +1453,11 @@ class GroupedFrame
1393
1453
  end
1394
1454
  out.each_with_object({}) do |(name, col), cols|
1395
1455
  name = @frame.__send__(:column_name_arg, name, "aggregate")
1396
- unless col.is_a?(CArray) && col.ndim >= 1 && col.shape[0] == ngroup
1456
+ unless col.is_a?(CArray) && col.ndim >= 1 && col.shape[0] == ngroups
1397
1457
  got = col.is_a?(CArray) ? "shape #{col.shape.inspect}" : col.class.to_s
1398
1458
  raise ArgumentError,
1399
1459
  "aggregate: #{name.inspect} must be a CArray with one value per group " \
1400
- "(#{ngroup}), got #{got}"
1460
+ "(#{ngroups}), got #{got}"
1401
1461
  end
1402
1462
  cols[name] = col
1403
1463
  end
@@ -1428,14 +1488,14 @@ class GroupedFrame
1428
1488
  end
1429
1489
 
1430
1490
  private def each_group_slice(in_name)
1431
- col = @frame[in_name]
1432
- ngroup.times do |k|
1491
+ col = @frame.__send__(:named_column, in_name, "aggregate")
1492
+ ngroups.times do |k|
1433
1493
  yield col[group_address(k), *([nil] * (col.ndim - 1))]
1434
1494
  end
1435
1495
  end
1436
1496
 
1437
1497
  private def each_group_frame
1438
- ngroup.times { |k| yield @frame[group_address(k)] }
1498
+ ngroups.times { |k| yield @frame[group_address(k)] }
1439
1499
  end
1440
1500
 
1441
1501
  # The first row of each group, in code order.
@@ -1445,13 +1505,13 @@ class GroupedFrame
1445
1505
  # group without rows keeps no row (UNDEF). With more groups the columns
1446
1506
  # are gathered through the sort anyway, so the first rows are read off it.
1447
1507
  private def first_rows
1448
- if ngroup > CACategoricalIterator::SCATTER_CATEGORIES_MAX
1449
- return group_perm[group_bounds[0...ngroup]]
1508
+ if ngroups > CACategoricalIterator::SCATTER_CATEGORIES_MAX
1509
+ return group_perm[group_bounds[0...ngroups]]
1450
1510
  end
1451
1511
  n = @cat.elements
1452
- first = CArray.int64(ngroup).fill(n)
1512
+ first = CArray.int64(ngroups).fill(n)
1453
1513
  first.scatter_min!(@cat.codes, CArray.int64(n).seq!)
1454
- first[first.eq(n)] = UNDEF if ngroup > 0
1514
+ first[first.eq(n)] = UNDEF if ngroups > 0
1455
1515
  first
1456
1516
  end
1457
1517