-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathops.go
More file actions
1117 lines (986 loc) · 26.6 KB
/
Copy pathops.go
File metadata and controls
1117 lines (986 loc) · 26.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package otters
import (
"fmt"
"math"
"slices"
"sort"
"strconv"
"strings"
"time"
)
// Filter creates a new DataFrame with rows that match the condition
func (df *DataFrame) Filter(column, operator string, value any) *DataFrame {
if df.err != nil {
return df
}
if err := df.validateColumnExists(column); err != nil {
return df.setError(err)
}
if err := df.validateNotEmpty(); err != nil {
return df.setError(err)
}
series := df.columns[column]
// Try optimized typed path first
matchingIndices, err := filterIndicesTyped(series, operator, value)
if err != nil {
return df.setError(wrapColumnError("Filter", column, err))
}
return df.selectRows(matchingIndices, "Filter")
}
// filterIndicesTyped returns matching indices using typed slice access to avoid boxing.
func filterIndicesTyped(series *Series, operator string, value any) ([]int, error) {
switch series.Type {
case Int64Type:
return filterInt64Indices(series.Data.([]int64), operator, value)
case Float64Type:
return filterFloat64Indices(series.Data.([]float64), operator, value)
case StringType:
return filterStringIndices(series.Data.([]string), operator, value)
case BoolType:
return filterBoolIndices(series.Data.([]bool), operator, value)
case TimeType:
return filterTimeIndices(series.Data.([]time.Time), operator, value)
}
return nil, nil
}
func filterInt64Indices(data []int64, op string, value any) ([]int, error) {
// A fractional comparison value cannot be truncated to int64 without
// changing the predicate (e.g. "== 2.5" would match 2); compare in
// float64 space instead.
if f, isFloat := value.(float64); isFloat && f != math.Trunc(f) {
indices := make([]int, 0, len(data)/4)
for i, v := range data {
if matchFloat64(float64(v), op, f) {
indices = append(indices, i)
}
}
return indices, nil
}
cmp, ok := toInt64(value)
if !ok {
return nil, newOpError("Filter", fmt.Sprintf("cannot convert %T to int64", value))
}
indices := make([]int, 0, len(data)/4)
for i, v := range data {
if matchInt64(v, op, cmp) {
indices = append(indices, i)
}
}
return indices, nil
}
func filterFloat64Indices(data []float64, op string, value any) ([]int, error) {
cmp, ok := toFloat64(value)
if !ok {
return nil, newOpError("Filter", fmt.Sprintf("cannot convert %T to float64", value))
}
indices := make([]int, 0, len(data)/4)
for i, v := range data {
if matchFloat64(v, op, cmp) {
indices = append(indices, i)
}
}
return indices, nil
}
func filterStringIndices(data []string, op string, value any) ([]int, error) {
cmp, ok := value.(string)
if !ok {
cmp = fmt.Sprintf("%v", value)
}
indices := make([]int, 0, len(data)/4)
for i, v := range data {
if matchString(v, op, cmp) {
indices = append(indices, i)
}
}
return indices, nil
}
func filterBoolIndices(data []bool, op string, value any) ([]int, error) {
cmp, ok := value.(bool)
if !ok {
return nil, newOpError("Filter", fmt.Sprintf("cannot convert %T to bool", value))
}
indices := make([]int, 0, len(data)/4)
for i, v := range data {
if matchBool(v, op, cmp) {
indices = append(indices, i)
}
}
return indices, nil
}
func filterTimeIndices(data []time.Time, op string, value any) ([]int, error) {
cmp, ok := value.(time.Time)
if !ok {
return nil, newOpError("Filter", fmt.Sprintf("cannot convert %T to time.Time", value))
}
indices := make([]int, 0, len(data)/4)
for i, v := range data {
if matchTime(v, op, cmp) {
indices = append(indices, i)
}
}
return indices, nil
}
func toInt64(v any) (int64, bool) {
switch x := v.(type) {
case int64:
return x, true
case int:
return int64(x), true
case float64:
return int64(x), true
}
return 0, false
}
func toFloat64(v any) (float64, bool) {
switch x := v.(type) {
case float64:
return x, true
case int64:
return float64(x), true
case int:
return float64(x), true
}
return 0, false
}
func matchInt64(v int64, op string, cmp int64) bool {
switch op {
case "==", "=":
return v == cmp
case "!=", "<>":
return v != cmp
case ">":
return v > cmp
case ">=":
return v >= cmp
case "<":
return v < cmp
case "<=":
return v <= cmp
}
return false
}
func matchFloat64(v float64, op string, cmp float64) bool {
switch op {
case "==", "=":
return v == cmp
case "!=", "<>":
return v != cmp
case ">":
return v > cmp
case ">=":
return v >= cmp
case "<":
return v < cmp
case "<=":
return v <= cmp
}
return false
}
func matchString(v, op, cmp string) bool {
switch op {
case "==", "=":
return v == cmp
case "!=", "<>":
return v != cmp
case ">":
return v > cmp
case ">=":
return v >= cmp
case "<":
return v < cmp
case "<=":
return v <= cmp
case "contains":
return strings.Contains(v, cmp)
case "startswith":
return strings.HasPrefix(v, cmp)
case "endswith":
return strings.HasSuffix(v, cmp)
}
return false
}
func matchBool(v bool, op string, cmp bool) bool {
switch op {
case "==", "=":
return v == cmp
case "!=", "<>":
return v != cmp
}
return false
}
func matchTime(v time.Time, op string, cmp time.Time) bool {
switch op {
case "==", "=":
return v.Equal(cmp)
case "!=", "<>":
return !v.Equal(cmp)
case ">":
return v.After(cmp)
case ">=":
return v.After(cmp) || v.Equal(cmp)
case "<":
return v.Before(cmp)
case "<=":
return v.Before(cmp) || v.Equal(cmp)
}
return false
}
// Select creates a new DataFrame with only the specified columns
func (df *DataFrame) Select(columns ...string) *DataFrame {
if df.err != nil {
return df
}
if len(columns) == 0 {
return df.setError(newOpError("Select", "at least one column must be specified"))
}
if err := df.validateColumnsExist(columns); err != nil {
return df.setError(err)
}
seen := make(map[string]bool, len(columns))
for _, colName := range columns {
if seen[colName] {
return df.setError(newColumnError("Select", colName, "column specified more than once"))
}
seen[colName] = true
}
newDf := NewDataFrame()
newDf.length = df.length
// Add selected columns in the order specified
for _, colName := range columns {
series := df.columns[colName].Copy()
if err := newDf.addSeriesUnsafe(series); err != nil {
return df.setError(wrapColumnError("Select", colName, err))
}
}
return newDf
}
// Drop creates a new DataFrame without the specified columns
func (df *DataFrame) Drop(columns ...string) *DataFrame {
if df.err != nil {
return df
}
if len(columns) == 0 {
return df.Copy() // No columns to drop, return copy
}
// Validate all columns exist
if err := df.validateColumnsExist(columns); err != nil {
return df.setError(err)
}
// Create set of columns to drop for O(1) lookup
dropSet := make(map[string]bool)
for _, col := range columns {
dropSet[col] = true
}
// Select all columns except the ones to drop
var keepColumns []string
for _, colName := range df.order {
if !dropSet[colName] {
keepColumns = append(keepColumns, colName)
}
}
if len(keepColumns) == 0 {
return df.setError(newOpError("Drop", "cannot drop all columns"))
}
return df.Select(keepColumns...)
}
// Sort creates a new DataFrame sorted by the specified column
func (df *DataFrame) Sort(column string, ascending bool) *DataFrame {
return df.SortBy([]string{column}, []bool{ascending})
}
// SortBy creates a new DataFrame sorted by multiple columns
func (df *DataFrame) SortBy(columns []string, ascending []bool) *DataFrame {
if df.err != nil {
return df
}
if len(columns) == 0 {
return df.setError(newOpError("SortBy", "at least one column must be specified"))
}
if len(columns) != len(ascending) {
return df.setError(newOpError("SortBy", "columns and ascending arrays must have the same length"))
}
if err := df.validateColumnsExist(columns); err != nil {
return df.setError(err)
}
if err := df.validateNotEmpty(); err != nil {
return df.setError(err)
}
// Create index array to sort
indices := make([]int, df.length)
for i := range indices {
indices[i] = i
}
// Build one typed comparator per sort column so the hot comparison loop
// touches typed slices directly instead of boxing values through Get.
comparators := make([]func(a, b int) int, len(columns))
for k, colName := range columns {
cmp := typedComparator(df.columns[colName])
if cmp == nil {
return df.setError(newColumnError("SortBy", colName, "unsupported column type for sorting"))
}
comparators[k] = cmp
}
// Sort indices based on column values. Ties break on the original row
// index, which makes the comparison a strict total order — the result is
// identical to a stable sort while keeping the faster unstable algorithm.
sort.Slice(indices, func(i, j int) bool {
rowI, rowJ := indices[i], indices[j]
// Compare by each column in order
for k, compare := range comparators {
cmp := compare(rowI, rowJ)
if cmp != 0 {
if ascending[k] {
return cmp < 0
}
return cmp > 0
}
}
return rowI < rowJ // Equal keys: preserve original row order
})
// Create new DataFrame with sorted rows
return df.selectRows(indices, "SortBy")
}
// uniqueFromSeries extracts unique values from a series.
func uniqueFromSeries(series *Series) []any {
switch series.Type {
case StringType:
return uniqueStrings(series.Data.([]string))
case Int64Type:
return uniqueInt64(series.Data.([]int64))
case Float64Type:
return uniqueFloat64(series.Data.([]float64))
case BoolType:
return uniqueBool(series.Data.([]bool))
case TimeType:
return uniqueTime(series.Data.([]time.Time))
}
return nil
}
func uniqueStrings(data []string) []any {
seen := make(map[string]bool, len(data)/4)
unique := make([]any, 0, len(data)/4)
for _, v := range data {
if !seen[v] {
seen[v] = true
unique = append(unique, v)
}
}
return unique
}
func uniqueInt64(data []int64) []any {
seen := make(map[string]bool, len(data)/4)
unique := make([]any, 0, len(data)/4)
for _, v := range data {
key := strconv.FormatInt(v, 10)
if !seen[key] {
seen[key] = true
unique = append(unique, v)
}
}
return unique
}
func uniqueFloat64(data []float64) []any {
seen := make(map[string]bool, len(data)/4)
unique := make([]any, 0, len(data)/4)
for _, v := range data {
key := strconv.FormatFloat(v, 'g', -1, 64)
if !seen[key] {
seen[key] = true
unique = append(unique, v)
}
}
return unique
}
func uniqueBool(data []bool) []any {
seen := make(map[string]bool, 2)
unique := make([]any, 0, 2)
for _, v := range data {
key := "false"
if v {
key = "true"
}
if !seen[key] {
seen[key] = true
unique = append(unique, v)
}
}
return unique
}
func uniqueTime(data []time.Time) []any {
seen := make(map[string]bool, len(data)/4)
unique := make([]any, 0, len(data)/4)
for _, v := range data {
key := v.String()
if !seen[key] {
seen[key] = true
unique = append(unique, v)
}
}
return unique
}
// Unique returns unique values from a specified column
func (df *DataFrame) Unique(column string) ([]any, error) {
if df.err != nil {
return nil, df.err
}
if err := df.validateColumnExists(column); err != nil {
return nil, err
}
return uniqueFromSeries(df.columns[column]), nil
}
// GroupBy groups the DataFrame by the specified column(s)
func (df *DataFrame) GroupBy(columns ...string) *GroupBy {
if df.err != nil {
return &GroupBy{df: df, err: df.err}
}
if len(columns) == 0 {
return &GroupBy{df: df, err: newOpError("GroupBy", "at least one column must be specified")}
}
if err := df.validateColumnsExist(columns); err != nil {
return &GroupBy{df: df, err: err}
}
return &GroupBy{
df: df,
columns: columns,
err: nil,
}
}
// Where is an alias for Filter (Pandas compatibility)
func (df *DataFrame) Where(column, operator string, value any) *DataFrame {
return df.Filter(column, operator, value)
}
// Query applies a simple query string to filter the DataFrame
func (df *DataFrame) Query(query string) *DataFrame {
if df.err != nil {
return df
}
// Parse simple queries like "age > 25" or "name == 'John Smith'"
parts := strings.Fields(query)
if len(parts) < 3 {
return df.setError(newOpError("Query", "query must be in format 'column operator value'"))
}
column := parts[0]
operator := parts[1]
valueStr := strings.Join(parts[2:], " ")
// Remove quotes if present
if strings.HasPrefix(valueStr, "'") && strings.HasSuffix(valueStr, "'") {
valueStr = strings.Trim(valueStr, "'")
}
if strings.HasPrefix(valueStr, "\"") && strings.HasSuffix(valueStr, "\"") {
valueStr = strings.Trim(valueStr, "\"")
}
// Convert value to appropriate type based on column type
if !df.HasColumn(column) {
return df.setError(newColumnError("Query", column, "column does not exist"))
}
columnType, _ := df.GetColumnType(column)
value, err := ConvertValue(valueStr, columnType)
if err != nil {
return df.setError(wrapColumnError("Query", column, err))
}
return df.Filter(column, operator, value)
}
// Reset index (currently a no-op, but maintains Pandas compatibility)
func (df *DataFrame) ResetIndex() *DataFrame {
if df.err != nil {
return df
}
return df.Copy()
}
// GroupBy represents a grouped DataFrame for aggregation operations
type GroupBy struct {
df *DataFrame
columns []string
err error
}
// Sum calculates the sum for each group
func (gb *GroupBy) Sum() (*DataFrame, error) {
return gb.aggregate("sum")
}
// Mean calculates the average for each group
func (gb *GroupBy) Mean() (*DataFrame, error) {
return gb.aggregate("mean")
}
// Count calculates the count for each group
func (gb *GroupBy) Count() (*DataFrame, error) {
return gb.aggregate("count")
}
// Min calculates the minimum for each group
func (gb *GroupBy) Min() (*DataFrame, error) {
return gb.aggregate("min")
}
// Max calculates the maximum for each group
func (gb *GroupBy) Max() (*DataFrame, error) {
return gb.aggregate("max")
}
// Internal helper methods
// selectSeriesRows extracts rows at indices from a series, returning new data slice.
func selectSeriesRows(series *Series, indices []int) any {
switch series.Type {
case StringType:
return selectStringRows(series.Data.([]string), indices)
case Int64Type:
return selectInt64Rows(series.Data.([]int64), indices)
case Float64Type:
return selectFloat64Rows(series.Data.([]float64), indices)
case BoolType:
return selectBoolRows(series.Data.([]bool), indices)
case TimeType:
return selectTimeRows(series.Data.([]time.Time), indices)
default:
return nil
}
}
func selectStringRows(data []string, indices []int) []string {
newSlice := make([]string, len(indices))
for i, idx := range indices {
newSlice[i] = data[idx]
}
return newSlice
}
func selectInt64Rows(data []int64, indices []int) []int64 {
newSlice := make([]int64, len(indices))
for i, idx := range indices {
newSlice[i] = data[idx]
}
return newSlice
}
func selectFloat64Rows(data []float64, indices []int) []float64 {
newSlice := make([]float64, len(indices))
for i, idx := range indices {
newSlice[i] = data[idx]
}
return newSlice
}
func selectBoolRows(data []bool, indices []int) []bool {
newSlice := make([]bool, len(indices))
for i, idx := range indices {
newSlice[i] = data[idx]
}
return newSlice
}
func selectTimeRows(data []time.Time, indices []int) []time.Time {
newSlice := make([]time.Time, len(indices))
for i, idx := range indices {
newSlice[i] = data[idx]
}
return newSlice
}
// emptySliceForType returns an empty slice for the given column type.
func emptySliceForType(colType ColumnType) any {
switch colType {
case StringType:
return []string{}
case Int64Type:
return []int64{}
case Float64Type:
return []float64{}
case BoolType:
return []bool{}
case TimeType:
return []time.Time{}
default:
return nil
}
}
// selectRows creates a new DataFrame with rows at the specified indices
func (df *DataFrame) selectRows(indices []int, operation string) *DataFrame {
if len(indices) == 0 {
newDf := NewDataFrame()
for _, colName := range df.order {
series := df.columns[colName]
newSeries, err := newSeriesOwned(series.Name, emptySliceForType(series.Type))
if err != nil {
return df.setError(wrapError(operation, err))
}
newDf.addSeriesUnsafe(newSeries)
}
return newDf
}
newDf := NewDataFrame()
newDf.length = len(indices)
for _, colName := range df.order {
series := df.columns[colName]
newData := selectSeriesRows(series, indices)
if newData == nil {
return df.setError(newOpError(operation, fmt.Sprintf("unsupported type for column %s", colName)))
}
newSeries, err := newSeriesOwned(series.Name, newData)
if err != nil {
return df.setError(wrapColumnError(operation, colName, err))
}
if err := newDf.addSeriesUnsafe(newSeries); err != nil {
return df.setError(wrapError(operation, err))
}
}
return newDf
}
// typedComparator returns a function comparing the values at two row indices
// of a series without boxing. Returns nil for unsupported types.
func typedComparator(series *Series) func(a, b int) int {
switch series.Type {
case StringType:
data := series.Data.([]string)
return func(a, b int) int { return compareStrings(data[a], data[b]) }
case Int64Type:
data := series.Data.([]int64)
return func(a, b int) int { return compareInt64(data[a], data[b]) }
case Float64Type:
data := series.Data.([]float64)
return func(a, b int) int { return compareFloat64(data[a], data[b]) }
case BoolType:
data := series.Data.([]bool)
return func(a, b int) int { return compareBool(data[a], data[b]) }
case TimeType:
data := series.Data.([]time.Time)
return func(a, b int) int { return compareTime(data[a], data[b]) }
default:
return nil
}
}
func compareStrings(a, b string) int {
if a < b {
return -1
}
if a > b {
return 1
}
return 0
}
func compareInt64(a, b int64) int {
if a < b {
return -1
}
if a > b {
return 1
}
return 0
}
func compareFloat64(a, b float64) int {
if a < b {
return -1
}
if a > b {
return 1
}
return 0
}
func compareBool(a, b bool) int {
if !a && b {
return -1
}
if a && !b {
return 1
}
return 0
}
func compareTime(a, b time.Time) int {
if a.Before(b) {
return -1
}
if a.After(b) {
return 1
}
return 0
}
// seriesValueToString extracts value at index i from series as string (no boxing).
func seriesValueToString(series *Series, i int) string {
switch series.Type {
case StringType:
return series.Data.([]string)[i]
case Int64Type:
return strconv.FormatInt(series.Data.([]int64)[i], 10)
case Float64Type:
return strconv.FormatFloat(series.Data.([]float64)[i], 'g', -1, 64)
case BoolType:
if series.Data.([]bool)[i] {
return "true"
}
return "false"
case TimeType:
return series.Data.([]time.Time)[i].String()
default:
return ""
}
}
// groupKey holds the string key and original values for a group.
type groupKey struct {
values []string
indices []int
}
// buildGroups creates group map from DataFrame rows.
func (gb *GroupBy) buildGroups() map[string]*groupKey {
groups := make(map[string]*groupKey)
// Pre-cache series pointers for grouping columns
groupSeries := make([]*Series, len(gb.columns))
for j, col := range gb.columns {
groupSeries[j] = gb.df.columns[col]
}
var key strings.Builder
key.Grow(64)
for i := 0; i < gb.df.length; i++ {
key.Reset()
values := make([]string, len(gb.columns))
for j, series := range groupSeries {
if j > 0 {
key.WriteByte(0)
}
part := seriesValueToString(series, i)
values[j] = part
key.WriteString(strconv.Itoa(len(part)))
key.WriteByte(':')
key.WriteString(part)
}
k := key.String()
if _, exists := groups[k]; !exists {
groups[k] = &groupKey{values: values}
}
groups[k].indices = append(groups[k].indices, i)
}
return groups
}
// aggregate performs aggregation operations for GroupBy
func (gb *GroupBy) aggregate(operation string) (*DataFrame, error) {
if gb.err != nil {
return nil, gb.err
}
groups := gb.buildGroups()
sortedKeys := sortGroupKeys(groups)
numGroups := len(sortedKeys)
groupColData := allocateGroupColumns(gb.columns, numGroups)
// Count is the size of each group, independent of any numeric columns.
if operation == "count" {
counts := make([]int64, 0, numGroups)
for _, k := range sortedKeys {
g := groups[k]
for j := range gb.columns {
groupColData[j] = append(groupColData[j], g.values[j])
}
counts = append(counts, int64(len(g.indices)))
}
return buildCountDataFrame(gb.columns, groupColData, counts)
}
numericCols := identifyNumericColumns(gb.df, gb.columns, numGroups)
if err := processGroups(gb, groups, sortedKeys, groupColData, numericCols, operation); err != nil {
return nil, err
}
return buildResultDataFrame(gb.columns, groupColData, numericCols)
}
// sortGroupKeys orders groups by their actual column values, not by the
// internal length-prefixed key encoding (which would sort "East" before
// "North" but also "Phone" before "Laptop", by key length first).
func sortGroupKeys(groups map[string]*groupKey) []string {
sortedKeys := make([]string, 0, len(groups))
for k := range groups {
sortedKeys = append(sortedKeys, k)
}
sort.Slice(sortedKeys, func(i, j int) bool {
a := groups[sortedKeys[i]].values
b := groups[sortedKeys[j]].values
for x := range a {
if a[x] != b[x] {
return a[x] < b[x]
}
}
return false
})
return sortedKeys
}
func allocateGroupColumns(columns []string, numGroups int) [][]string {
groupColData := make([][]string, len(columns))
for j := range columns {
groupColData[j] = make([]string, 0, numGroups)
}
return groupColData
}
type numericCol struct {
name string
data []float64
}
func identifyNumericColumns(df *DataFrame, groupColumns []string, numGroups int) []numericCol {
var numericCols []numericCol
for _, colName := range df.order {
if contains(groupColumns, colName) {
continue
}
colType, _ := df.GetColumnType(colName)
if colType == Int64Type || colType == Float64Type {
numericCols = append(numericCols, numericCol{
name: colName,
data: make([]float64, 0, numGroups),
})
}
}
return numericCols
}
func processGroups(gb *GroupBy, groups map[string]*groupKey, sortedKeys []string, groupColData [][]string, numericCols []numericCol, operation string) error {
for _, k := range sortedKeys {
g := groups[k]
for j := range gb.columns {
groupColData[j] = append(groupColData[j], g.values[j])
}
for i := range numericCols {
aggValue, err := gb.calculateAggregation(numericCols[i].name, g.indices, operation)
if err != nil {
return err
}
numericCols[i].data = append(numericCols[i].data, aggValue)
}
}
return nil
}
// buildCountDataFrame builds the GroupBy.Count result: group columns plus a
// "count" column holding each group's row count.
func buildCountDataFrame(columns []string, groupColData [][]string, counts []int64) (*DataFrame, error) {
countName := "count"
for contains(columns, countName) {
countName += "_"
}
resultSeries := make([]*Series, 0, len(columns)+1)
for j, col := range columns {
s, err := newSeriesOwned(col, groupColData[j])
if err != nil {
return nil, err
}
resultSeries = append(resultSeries, s)
}
countSeries, err := newSeriesOwned(countName, counts)
if err != nil {
return nil, err
}
resultSeries = append(resultSeries, countSeries)
return NewDataFrameFromSeries(resultSeries...)
}
func buildResultDataFrame(columns []string, groupColData [][]string, numericCols []numericCol) (*DataFrame, error) {
resultSeries := make([]*Series, 0, len(columns)+len(numericCols))
for j, col := range columns {
s, err := newSeriesOwned(col, groupColData[j])
if err != nil {
return nil, err
}
resultSeries = append(resultSeries, s)
}
for _, nc := range numericCols {
s, err := newSeriesOwned(nc.name, nc.data)
if err != nil {
return nil, err
}
resultSeries = append(resultSeries, s)
}
return NewDataFrameFromSeries(resultSeries...)
}
// calculateAggregation calculates aggregation for a column and indices.
// Optimized to access typed slices directly, avoiding per-row interface{} boxing.
func (gb *GroupBy) calculateAggregation(column string, indices []int, operation string) (float64, error) {
series := gb.df.columns[column]
n := len(indices)
if n == 0 {
return 0, nil
}
// Fast path: access typed slice directly, compute aggregation in one pass
switch series.Type {