-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataframe.go
More file actions
1391 lines (1247 loc) · 36 KB
/
dataframe.go
File metadata and controls
1391 lines (1247 loc) · 36 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 fileframe
import (
"cmp"
"encoding/csv"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"github.com/nao1215/fileparser"
)
// DataFrame is a simple representation of tabular data.
// It stores data in row-oriented format with immediate execution (no lazy evaluation).
type DataFrame struct {
columns []string // column names
rows []map[string]any // row data
}
// copyRow creates a deep copy of a row to prevent shared references.
// This is critical for maintaining immutability of DataFrame operations.
func copyRow(row map[string]any) map[string]any {
copied := make(map[string]any, len(row))
for k, v := range row {
copied[k] = v
}
return copied
}
// NewDataFrame creates a DataFrame from an io.Reader.
// It supports CSV, TSV, LTSV, XLSX, and Parquet formats.
//
// Example:
//
// f, _ := os.Open("data.csv")
// defer f.Close()
// df, err := fileframe.NewDataFrame(f, fileframe.CSV)
func NewDataFrame(reader io.Reader, fileType FileType) (*DataFrame, error) {
if reader == nil {
return nil, errors.New("reader cannot be nil")
}
// Use fileparser package directly for lightweight parsing
result, err := fileparser.Parse(reader, fileType)
if err != nil {
return nil, fmt.Errorf("failed to parse: %w", err)
}
// Convert parser.TableData to DataFrame
columns := result.Headers
dfRows := make([]map[string]any, len(result.Records))
for i, record := range result.Records {
row := make(map[string]any, len(columns))
for j, col := range columns {
if j < len(record) {
row[col] = convertStringValue(record[j], result.ColumnTypes[j])
} else {
row[col] = nil
}
}
dfRows[i] = row
}
return &DataFrame{
columns: columns,
rows: dfRows,
}, nil
}
// NewDataFrameFromPath creates a DataFrame from a file path.
// It automatically detects the file type and handles compressed files
// (gzip, bzip2, xz, zstd, zlib, snappy, s2, lz4).
//
// Supported formats: CSV, TSV, LTSV, XLSX, Parquet, and their compressed variants.
// For XLSX files with multiple sheets, the first sheet is used.
//
// Example:
//
// df, err := fileframe.NewDataFrameFromPath("data.csv.gz")
// df, err := fileframe.NewDataFrameFromPath("data.csv.snappy")
func NewDataFrameFromPath(path string) (*DataFrame, error) {
// Detect file type from path
fileType := fileparser.DetectFileType(path)
if fileType == fileparser.Unsupported {
return nil, fmt.Errorf("unsupported file type: %s", path)
}
// Open file for parsing
file, err := os.Open(filepath.Clean(path))
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
// Use fileparser package directly for parsing (handles decompression internally)
result, err := fileparser.Parse(file, fileType)
if err != nil {
return nil, fmt.Errorf("failed to parse: %w", err)
}
// Convert parser.TableData to DataFrame
columns := result.Headers
dfRows := make([]map[string]any, len(result.Records))
for i, record := range result.Records {
row := make(map[string]any, len(columns))
for j, col := range columns {
if j < len(record) {
row[col] = convertStringValue(record[j], result.ColumnTypes[j])
} else {
row[col] = nil
}
}
dfRows[i] = row
}
return &DataFrame{
columns: columns,
rows: dfRows,
}, nil
}
// convertStringValue converts a string value to the appropriate Go type based on ColumnType.
func convertStringValue(s string, ct fileparser.ColumnType) any {
switch ct {
case fileparser.TypeInteger:
if s == "" {
return s
}
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
return i
}
return s
case fileparser.TypeReal:
if s == "" {
return s
}
if f, err := strconv.ParseFloat(s, 64); err == nil {
return f
}
return s
default:
return s
}
}
// NewDataFrameFromRecords creates a DataFrame from a slice of maps.
// Each map represents a row with column names as keys.
// Column order is determined by processing records in order, and within each record,
// keys are sorted alphabetically. New columns are appended as they are encountered.
//
// Example:
//
// records := []map[string]any{
// {"name": "Alice", "age": 30},
// {"name": "Bob", "age": 25},
// }
// df := fileframe.NewDataFrameFromRecords(records)
func NewDataFrameFromRecords(records []map[string]any) *DataFrame {
if len(records) == 0 {
return &DataFrame{
columns: []string{},
rows: []map[string]any{},
}
}
// Extract column names preserving first-seen order
var columns []string
columnSeen := make(map[string]struct{})
for _, record := range records {
// For deterministic iteration within each record, sort keys
recordKeys := make([]string, 0, len(record))
for col := range record {
recordKeys = append(recordKeys, col)
}
slices.Sort(recordKeys)
for _, col := range recordKeys {
if _, seen := columnSeen[col]; !seen {
columnSeen[col] = struct{}{}
columns = append(columns, col)
}
}
}
// Copy all rows to ensure immutability
rows := make([]map[string]any, len(records))
for i, record := range records {
rows[i] = copyRow(record)
}
return &DataFrame{
columns: columns,
rows: rows,
}
}
// Columns returns a copy of the column names.
func (df *DataFrame) Columns() []string {
result := make([]string, len(df.columns))
copy(result, df.columns)
return result
}
// Len returns the number of rows in the DataFrame.
func (df *DataFrame) Len() int {
return len(df.rows)
}
// ToRecords returns the data as a slice of maps.
// Each map is a copy to ensure immutability.
func (df *DataFrame) ToRecords() []map[string]any {
result := make([]map[string]any, len(df.rows))
for i, row := range df.rows {
result[i] = copyRow(row)
}
return result
}
// ToCSV writes the DataFrame to a CSV file.
//
// Example:
//
// err := df.ToCSV("output.csv")
func (df *DataFrame) ToCSV(path string) error {
return df.toDelimitedFile(path, ',')
}
// ToTSV writes the DataFrame to a TSV file.
//
// Example:
//
// err := df.ToTSV("output.tsv")
func (df *DataFrame) ToTSV(path string) error {
return df.toDelimitedFile(path, '\t')
}
// toDelimitedFile writes the DataFrame to a file with the specified delimiter.
func (df *DataFrame) toDelimitedFile(path string, delimiter rune) error {
f, err := os.Create(path) //nolint:gosec // path is provided by the user
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer f.Close()
writer := csv.NewWriter(f)
writer.Comma = delimiter
// Write header
if err := writer.Write(df.columns); err != nil {
return fmt.Errorf("failed to write header: %w", err)
}
// Write rows
for _, row := range df.rows {
record := make([]string, len(df.columns))
for i, col := range df.columns {
record[i] = formatValue(row[col])
}
if err := writer.Write(record); err != nil {
return fmt.Errorf("failed to write row: %w", err)
}
}
// Flush buffered data and check for errors
writer.Flush()
if err := writer.Error(); err != nil {
return fmt.Errorf("failed to flush writer: %w", err)
}
return nil
}
// formatValue converts a value to its string representation for CSV output.
func formatValue(v any) string {
if v == nil {
return ""
}
return fmt.Sprintf("%v", v)
}
// Select returns a new DataFrame with only the specified columns.
// Columns that do not exist are silently ignored.
//
// Example:
//
// selected := df.Select("name", "age")
func (df *DataFrame) Select(columns ...string) *DataFrame {
if len(columns) == 0 {
return &DataFrame{
columns: []string{},
rows: []map[string]any{},
}
}
// Filter to only existing columns, preserving order
existingCols := make(map[string]struct{}, len(df.columns))
for _, col := range df.columns {
existingCols[col] = struct{}{}
}
selectedCols := make([]string, 0, len(columns))
for _, col := range columns {
if _, exists := existingCols[col]; exists {
selectedCols = append(selectedCols, col)
}
}
// Create new rows with only selected columns
newRows := make([]map[string]any, len(df.rows))
for i, row := range df.rows {
newRow := make(map[string]any, len(selectedCols))
for _, col := range selectedCols {
newRow[col] = row[col]
}
newRows[i] = newRow
}
return &DataFrame{
columns: selectedCols,
rows: newRows,
}
}
// Filter returns a new DataFrame containing only rows that satisfy the predicate.
// The predicate function receives a copy of each row to prevent accidental mutation
// of the original DataFrame.
//
// Example:
//
// filtered := df.Filter(func(row map[string]any) bool {
// age, ok := row["age"].(int64)
// return ok && age >= 18
// })
func (df *DataFrame) Filter(fn func(row map[string]any) bool) *DataFrame {
if fn == nil {
return df.clone()
}
var filtered []map[string]any
for _, row := range df.rows {
// Pass a copy to the predicate to prevent mutation of original data
if fn(copyRow(row)) {
filtered = append(filtered, copyRow(row))
}
}
columns := make([]string, len(df.columns))
copy(columns, df.columns)
return &DataFrame{
columns: columns,
rows: filtered,
}
}
// Mutate returns a new DataFrame with a new or modified column.
// The function receives a copy of each row and returns the value for the new column.
// The original DataFrame is not modified.
//
// If the column name is empty or the function is nil, Mutate returns a clone
// of the original DataFrame without any modifications.
//
// Example:
//
// mutated := df.Mutate("full_name", func(row map[string]any) any {
// first := row["first_name"].(string)
// last := row["last_name"].(string)
// return first + " " + last
// })
func (df *DataFrame) Mutate(column string, fn func(row map[string]any) any) *DataFrame {
if fn == nil || column == "" {
return df.clone()
}
newRows := make([]map[string]any, len(df.rows))
for i, row := range df.rows {
newRow := copyRow(row)
// Pass a copy to the function to prevent mutation of original data
newRow[column] = fn(copyRow(row))
newRows[i] = newRow
}
// Update columns list if new column
isNewColumn := true
for _, col := range df.columns {
if col == column {
isNewColumn = false
break
}
}
var newColumns []string
if isNewColumn {
newColumns = make([]string, len(df.columns), len(df.columns)+1)
copy(newColumns, df.columns)
newColumns = append(newColumns, column)
} else {
newColumns = make([]string, len(df.columns))
copy(newColumns, df.columns)
}
return &DataFrame{
columns: newColumns,
rows: newRows,
}
}
// clone creates a deep copy of the DataFrame.
func (df *DataFrame) clone() *DataFrame {
columns := make([]string, len(df.columns))
copy(columns, df.columns)
rows := make([]map[string]any, len(df.rows))
for i, row := range df.rows {
rows[i] = copyRow(row)
}
return &DataFrame{
columns: columns,
rows: rows,
}
}
// JoinType represents the type of join operation.
// Four join types are supported: InnerJoin, LeftJoin, RightJoin, and OuterJoin.
type JoinType int
const (
// InnerJoin returns only rows that have matching values in both DataFrames.
// This is the most restrictive join type - rows without matches are excluded.
//
// Example: If users has ids [1, 2, 3] and orders has user_ids [1, 2, 4],
// an inner join returns only rows for users 1 and 2.
InnerJoin JoinType = iota
// LeftJoin returns all rows from the left DataFrame and matched rows from the right DataFrame.
// For left rows without matches, the right columns will have nil values.
//
// Example: If users has ids [1, 2, 3] and orders has user_ids [1, 2],
// a left join returns all 3 users, with user 3 having nil for order columns.
LeftJoin
// RightJoin returns all rows from the right DataFrame and matched rows from the left DataFrame.
// For right rows without matches, the left columns will have nil values.
//
// Example: If users has ids [1, 2] and orders has user_ids [1, 2, 3],
// a right join returns all 3 orders, with order 3 having nil for user columns.
RightJoin
// OuterJoin returns all rows from both DataFrames.
// Unmatched rows will have nil values for columns from the other DataFrame.
// This is the most inclusive join type - no rows are excluded.
//
// Example: If users has ids [1, 2] and orders has user_ids [2, 3],
// an outer join returns users 1, 2 and orders 2, 3 (4 rows total).
OuterJoin
)
// JoinOption specifies options for the Join operation.
//
// On field specifies the join column(s):
// - One column: Used for both DataFrames (e.g., On: []string{"id"})
// - Two columns: First for left DataFrame, second for right (e.g., On: []string{"id", "user_id"})
//
// How field specifies the join type (InnerJoin, LeftJoin, RightJoin, OuterJoin).
//
// Example:
//
// // Same column name in both DataFrames
// opt := fileframe.JoinOption{On: []string{"id"}, How: fileframe.InnerJoin}
//
// // Different column names
// opt := fileframe.JoinOption{On: []string{"id", "user_id"}, How: fileframe.LeftJoin}
type JoinOption struct {
// On specifies the column(s) to join on.
// If one column is specified, it is used for both DataFrames.
// If two columns are specified, the first is for the left DataFrame and the second for the right.
On []string
// How specifies the type of join (InnerJoin, LeftJoin, RightJoin, OuterJoin).
How JoinType
}
// Join combines two DataFrames based on a common column or column pair.
// This method enables SQL-like join operations between DataFrames.
//
// Join Types:
// - InnerJoin: Returns only matching rows from both DataFrames
// - LeftJoin: Returns all left rows, with nil for unmatched right columns
// - RightJoin: Returns all right rows, with nil for unmatched left columns
// - OuterJoin: Returns all rows from both, with nil for unmatched columns
//
// Column Handling:
// - The join column from the right DataFrame is excluded from the result
// - Conflicting column names are prefixed with "right_"
// - Result column order: left columns first, then right columns
//
// Limitations:
// - Currently supports joining on a single column pair (1 or 2 columns in On)
// - For complex joins with multiple keys, consider using filesql
//
// Example - Inner Join with same column name:
//
// users := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"id": 1, "name": "Alice"},
// {"id": 2, "name": "Bob"},
// })
// orders := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"id": 1, "product": "Laptop"},
// {"id": 1, "product": "Mouse"},
// })
// result, err := users.Join(orders, fileframe.JoinOption{
// On: []string{"id"},
// How: fileframe.InnerJoin,
// })
// // Result: [{id:1, name:Alice, product:Laptop}, {id:1, name:Alice, product:Mouse}]
//
// Example - Left Join with different column names:
//
// users := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"user_id": 1, "name": "Alice"},
// {"user_id": 2, "name": "Bob"},
// {"user_id": 3, "name": "Charlie"},
// })
// orders := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"customer_id": 1, "product": "Laptop"},
// })
// result, err := users.Join(orders, fileframe.JoinOption{
// On: []string{"user_id", "customer_id"},
// How: fileframe.LeftJoin,
// })
// // Result includes all 3 users; Bob and Charlie have nil for product
func (df *DataFrame) Join(other *DataFrame, opt JoinOption) (*DataFrame, error) {
if other == nil {
return nil, errors.New("other DataFrame cannot be nil")
}
if len(opt.On) == 0 {
return nil, errors.New("join requires at least one column")
}
if len(opt.On) > 2 {
return nil, errors.New("join on more than 2 columns is not supported yet")
}
// Determine left and right join columns
leftCol := opt.On[0]
rightCol := leftCol
if len(opt.On) == 2 {
rightCol = opt.On[1]
}
// Validate columns exist
if !df.hasColumn(leftCol) {
return nil, fmt.Errorf("column %q not found in left DataFrame", leftCol)
}
if !other.hasColumn(rightCol) {
return nil, fmt.Errorf("column %q not found in right DataFrame", rightCol)
}
// Build index for right DataFrame, mapping key -> (row index, row data)
type indexedRow struct {
index int
row map[string]any
}
rightIndex := make(map[any][]indexedRow)
for i, row := range other.rows {
key := row[rightCol]
rightIndex[key] = append(rightIndex[key], indexedRow{index: i, row: row})
}
// Build result columns (left columns + right columns excluding join column)
rightColsToAdd := make([]string, 0, len(other.columns))
rightColsOriginal := make([]string, 0, len(other.columns))
for _, col := range other.columns {
if col != rightCol {
rightColsOriginal = append(rightColsOriginal, col)
// Handle column name conflicts by prefixing with "right_"
finalCol := col
if df.hasColumn(col) {
finalCol = "right_" + col
}
rightColsToAdd = append(rightColsToAdd, finalCol)
}
}
resultColumns := make([]string, 0, len(df.columns)+len(rightColsToAdd))
resultColumns = append(resultColumns, df.columns...)
resultColumns = append(resultColumns, rightColsToAdd...)
var resultRows []map[string]any
// Track which right row indices have been matched (for outer join)
rightMatched := make(map[int]bool)
// Process left rows
for _, leftRow := range df.rows {
leftKey := leftRow[leftCol]
indexedRows, found := rightIndex[leftKey]
if found {
// Create joined rows and mark right rows as matched
for _, ir := range indexedRows {
rightMatched[ir.index] = true
newRow := copyRow(leftRow)
for i, col := range rightColsOriginal {
newRow[rightColsToAdd[i]] = ir.row[col]
}
resultRows = append(resultRows, newRow)
}
} else if opt.How == LeftJoin || opt.How == OuterJoin {
// No match, but include left row with nil for right columns
newRow := copyRow(leftRow)
for _, col := range rightColsToAdd {
newRow[col] = nil
}
resultRows = append(resultRows, newRow)
}
}
// For right join and outer join, add unmatched right rows
if opt.How == RightJoin || opt.How == OuterJoin {
for i, rightRow := range other.rows {
if !rightMatched[i] {
newRow := make(map[string]any, len(resultColumns))
// Set left columns to nil
for _, col := range df.columns {
if col == leftCol {
newRow[col] = rightRow[rightCol]
} else {
newRow[col] = nil
}
}
// Set right columns
for j, col := range rightColsOriginal {
newRow[rightColsToAdd[j]] = rightRow[col]
}
resultRows = append(resultRows, newRow)
}
}
}
return &DataFrame{
columns: resultColumns,
rows: resultRows,
}, nil
}
// hasColumn checks if the DataFrame has a column with the given name.
func (df *DataFrame) hasColumn(name string) bool {
for _, col := range df.columns {
if col == name {
return true
}
}
return false
}
// Concat concatenates multiple DataFrames vertically (row-wise).
// This is useful for combining data from multiple sources with the same schema.
//
// Requirements:
// - All DataFrames must have exactly the same columns in the same order
// - If columns differ, use ConcatAll instead for flexible concatenation
//
// Returns an error if:
// - Any DataFrame is nil
// - Columns don't match (different names or different order)
//
// Example - Combining monthly data:
//
// jan := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"month": "Jan", "sales": 100},
// })
// feb := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"month": "Feb", "sales": 150},
// })
// mar := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"month": "Mar", "sales": 200},
// })
// quarterly, err := jan.Concat(feb, mar)
// // Result: 3 rows with all monthly data
//
// Example - Combining data from multiple CSV files:
//
// df1, _ := fileframe.NewDataFrameFromPath("data_2024_01.csv")
// df2, _ := fileframe.NewDataFrameFromPath("data_2024_02.csv")
// combined, err := df1.Concat(df2)
func (df *DataFrame) Concat(others ...*DataFrame) (*DataFrame, error) {
if len(others) == 0 {
return df.clone(), nil
}
// Validate all DataFrames have the same columns
for i, other := range others {
if other == nil {
return nil, fmt.Errorf("DataFrame at index %d is nil", i+1)
}
if !slices.Equal(df.columns, other.columns) {
return nil, fmt.Errorf("DataFrame at index %d has different columns: expected %v, got %v",
i+1, df.columns, other.columns)
}
}
// Calculate total rows
totalRows := len(df.rows)
for _, other := range others {
totalRows += len(other.rows)
}
// Build result
resultColumns := make([]string, len(df.columns))
copy(resultColumns, df.columns)
resultRows := make([]map[string]any, 0, totalRows)
// Add rows from first DataFrame
for _, row := range df.rows {
resultRows = append(resultRows, copyRow(row))
}
// Add rows from other DataFrames
for _, other := range others {
for _, row := range other.rows {
resultRows = append(resultRows, copyRow(row))
}
}
return &DataFrame{
columns: resultColumns,
rows: resultRows,
}, nil
}
// ConcatAll concatenates multiple DataFrames vertically, automatically handling
// different column sets by taking the union of all columns.
// This is a standalone function (not a method) that accepts any number of DataFrames.
//
// Column Handling:
// - Columns from all DataFrames are collected into a union set
// - Columns are sorted alphabetically for deterministic output
// - Missing values in rows are set to nil
//
// Nil DataFrames are silently skipped, making this safe for optional data.
//
// Use Cases:
// - Combining data from different sources with overlapping schemas
// - Merging datasets that evolved over time with different columns
// - Appending new data with additional fields to existing data
//
// Example - Combining data with different schemas:
//
// users := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"name": "Alice", "age": 30},
// })
// contacts := fileframe.NewDataFrameFromRecords([]map[string]any{
// {"name": "Bob", "email": "bob@example.com"},
// })
// result, err := fileframe.ConcatAll(users, contacts)
// // Result columns: ["age", "email", "name"] (sorted alphabetically)
// // Alice has nil for email, Bob has nil for age
//
// Example - Combining CSV and TSV data:
//
// csv, _ := fileframe.NewDataFrameFromPath("users.csv")
// tsv, _ := fileframe.NewDataFrameFromPath("extra_info.tsv")
// combined, err := fileframe.ConcatAll(csv, tsv)
func ConcatAll(frames ...*DataFrame) (*DataFrame, error) {
if len(frames) == 0 {
return &DataFrame{
columns: []string{},
rows: []map[string]any{},
}, nil
}
// Collect all unique columns
columnSet := make(map[string]struct{})
for _, df := range frames {
if df == nil {
continue
}
for _, col := range df.columns {
columnSet[col] = struct{}{}
}
}
// Sort columns for deterministic order
allColumns := make([]string, 0, len(columnSet))
for col := range columnSet {
allColumns = append(allColumns, col)
}
slices.Sort(allColumns)
// Calculate total rows
totalRows := 0
for _, df := range frames {
if df != nil {
totalRows += len(df.rows)
}
}
// Build result rows
resultRows := make([]map[string]any, 0, totalRows)
for _, df := range frames {
if df == nil {
continue
}
for _, row := range df.rows {
newRow := make(map[string]any, len(allColumns))
for _, col := range allColumns {
if val, exists := row[col]; exists {
newRow[col] = val
} else {
newRow[col] = nil
}
}
resultRows = append(resultRows, newRow)
}
}
return &DataFrame{
columns: allColumns,
rows: resultRows,
}, nil
}
// SortOrder specifies the order for sorting.
type SortOrder int
const (
// Ascending sorts values from smallest to largest.
Ascending SortOrder = iota
// Descending sorts values from largest to smallest.
Descending
)
// SortOption specifies options for the Sort operation.
type SortOption struct {
// Column is the column name to sort by.
Column string
// Order specifies ascending or descending sort order.
Order SortOrder
}
// Sort returns a new DataFrame sorted by the specified column.
// Supports sorting by string, int64, and float64 values.
// Nil values are placed at the end regardless of sort order.
//
// Example:
//
// sorted := df.Sort("age", fileframe.Ascending)
func (df *DataFrame) Sort(column string, order SortOrder) (*DataFrame, error) {
if !df.hasColumn(column) {
return nil, fmt.Errorf("column %q not found", column)
}
// Clone rows for sorting
sortedRows := make([]map[string]any, len(df.rows))
for i, row := range df.rows {
sortedRows[i] = copyRow(row)
}
// Sort using Go's slices.SortFunc
slices.SortFunc(sortedRows, func(a, b map[string]any) int {
aVal := a[column]
bVal := b[column]
// Handle nil values - always sort to end
if aVal == nil && bVal == nil {
return 0
}
if aVal == nil {
return 1
}
if bVal == nil {
return -1
}
result := compareValues(aVal, bVal)
if order == Descending {
result = -result
}
return result
})
columns := make([]string, len(df.columns))
copy(columns, df.columns)
return &DataFrame{
columns: columns,
rows: sortedRows,
}, nil
}
// SortBy returns a new DataFrame sorted by multiple columns.
// Columns are sorted in the order specified (first column has highest priority).
//
// Example:
//
// sorted, err := df.SortBy(
// fileframe.SortOption{Column: "category", Order: fileframe.Ascending},
// fileframe.SortOption{Column: "price", Order: fileframe.Descending},
// )
func (df *DataFrame) SortBy(options ...SortOption) (*DataFrame, error) {
if len(options) == 0 {
return df.clone(), nil
}
// Validate all columns exist
for _, opt := range options {
if !df.hasColumn(opt.Column) {
return nil, fmt.Errorf("column %q not found", opt.Column)
}
}
// Clone rows for sorting
sortedRows := make([]map[string]any, len(df.rows))
for i, row := range df.rows {
sortedRows[i] = copyRow(row)
}
// Sort using multiple columns
slices.SortFunc(sortedRows, func(a, b map[string]any) int {
for _, opt := range options {
aVal := a[opt.Column]
bVal := b[opt.Column]
// Handle nil values - always sort to end
if aVal == nil && bVal == nil {
continue
}
if aVal == nil {
return 1
}
if bVal == nil {
return -1
}
result := compareValues(aVal, bVal)
if opt.Order == Descending {
result = -result
}
if result != 0 {
return result
}
}
return 0
})
columns := make([]string, len(df.columns))
copy(columns, df.columns)
return &DataFrame{
columns: columns,
rows: sortedRows,
}, nil
}
// compareValues compares two values and returns -1, 0, or 1.
// Supports string, int64, float64 comparisons.
func compareValues(a, b any) int {
switch aTyped := a.(type) {
case string:
if bTyped, ok := b.(string); ok {
return cmp.Compare(aTyped, bTyped)
}
case int64:
switch bTyped := b.(type) {
case int64:
return cmp.Compare(aTyped, bTyped)
case float64:
return cmp.Compare(float64(aTyped), bTyped)
}
case float64:
switch bTyped := b.(type) {
case float64:
return cmp.Compare(aTyped, bTyped)
case int64:
return cmp.Compare(aTyped, float64(bTyped))
}
case int:
switch bTyped := b.(type) {
case int:
return cmp.Compare(aTyped, bTyped)
case int64:
return cmp.Compare(int64(aTyped), bTyped)
case float64:
return cmp.Compare(float64(aTyped), bTyped)
}
}
// Fallback: compare string representations
return cmp.Compare(fmt.Sprintf("%v", a), fmt.Sprintf("%v", b))
}
// Distinct returns a new DataFrame with duplicate rows removed.
// Two rows are considered duplicates if all their column values are equal.
//
// Example: