forked from kfultz07/go-dataframe
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
1226 lines (1042 loc) · 32.6 KB
/
main.go
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 dataframe
import (
"bytes"
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"math"
"os"
"reflect"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/exp/slices"
)
type Record struct {
Data []string
}
type DataFrame struct {
FrameRecords []Record
Headers map[string]int
}
type StreamingRecord struct {
Data []string
Headers map[string]int
}
// Return the value of the specified field.
func (x StreamingRecord) Val(fieldName string) string {
if _, ok := x.Headers[fieldName]; !ok {
panic(fmt.Errorf("The provided field %s is not a valid field in the dataframe.", fieldName))
}
return x.Data[x.Headers[fieldName]]
}
// Converts the value from a string to float64
func (x StreamingRecord) ConvertToFloat(fieldName string) float64 {
value, err := strconv.ParseFloat(x.Val(fieldName), 64)
if err != nil {
log.Fatalf("Could Not Convert to float64: %v", err)
}
return value
}
// Converts the value from a string to int64
func (x StreamingRecord) ConvertToInt(fieldName string) int64 {
value, err := strconv.ParseInt(x.Val(fieldName), 0, 64)
if err != nil {
log.Fatalf("Could Not Convert to int64: %v", err)
}
return value
}
// Generate a new empty DataFrame.
func CreateNewDataFrame(headers []string) DataFrame {
myRecords := []Record{}
theHeaders := make(map[string]int)
// Add headers to map in correct order
for i := 0; i < len(headers); i++ {
theHeaders[headers[i]] = i
}
newFrame := DataFrame{FrameRecords: myRecords, Headers: theHeaders}
return newFrame
}
// Generate a new DataFrame sourced from a csv file.
func CreateDataFrame(path, fileName string) DataFrame {
// Check user entries
if path[len(path)-1:] != "/" {
path = path + "/"
}
if strings.Contains(fileName, ".csv") != true {
fileName = fileName + ".csv"
}
// Open the CSV file
recordFile, err := os.Open(path + fileName)
if err != nil {
log.Fatalf("Error opening the file. Please ensure the path and filename are correct. Message: %v", err)
}
// Setup the reader
reader := csv.NewReader(recordFile)
return CreateDataFrameFromCsvReader(reader)
}
// Generate a new DataFrame sourced from an array of bytes containing csv data.
func CreateDataFrameFromBytes(b []byte) DataFrame {
// Setup the reader
reader := csv.NewReader(bytes.NewReader(b))
return CreateDataFrameFromCsvReader(reader)
}
// Generate a new DataFrame sourced from a csv reader.
func CreateDataFrameFromCsvReader(reader *csv.Reader) DataFrame {
// Read the records
header, err := reader.Read()
if err != nil {
log.Fatalf("Error reading the records: %v", err)
}
// Remove Byte Order Marker for UTF-8 files
for i, each := range header {
byteSlice := []byte(each)
if byteSlice[0] == 239 && byteSlice[1] == 187 && byteSlice[2] == 191 {
header[i] = each[3:]
}
}
headers := make(map[string]int)
for i, columnName := range header {
headers[columnName] = i
}
// Empty slice to store Records
s := []Record{}
// Loop over the records and create Record objects to be stored
for i := 0; ; i++ {
record, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Fatalf("Error in record loop: %v", err)
}
// Create new Record
x := Record{Data: []string{}}
// Loop over records and add to Data field of Record struct
for _, r := range record {
x.Data = append(x.Data, r)
}
s = append(s, x)
}
newFrame := DataFrame{FrameRecords: s, Headers: headers}
return newFrame
}
// Stream rows of data from a csv file to be processed. Streaming data is preferred when dealing with large files
// and memory usage needs to be considered. Results are streamed via a channel with a StreamingRecord type.
func Stream(path, fileName string, c chan StreamingRecord) {
defer close(c)
// Check user entries
if path[len(path)-1:] != "/" {
path = path + "/"
}
if strings.Contains(fileName, ".csv") != true {
fileName = fileName + ".csv"
}
// Open the CSV file
recordFile, err := os.Open(path + fileName)
if err != nil {
log.Fatalf("Error opening the file. Please ensure the path and filename are correct. Message: %v", err)
}
// Setup the reader
reader := csv.NewReader(recordFile)
// Read the records
header, err := reader.Read()
if err != nil {
log.Fatalf("Error reading the records: %v", err)
}
// Remove Byte Order Marker for UTF-8 files
for i, each := range header {
byteSlice := []byte(each)
if byteSlice[0] == 239 && byteSlice[1] == 187 && byteSlice[2] == 191 {
header[i] = each[3:]
}
}
headers := make(map[string]int)
for i, columnName := range header {
headers[columnName] = i
}
// Loop over the records and create Record objects to be stored
for i := 0; ; i++ {
record, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Fatalf("Error in record loop: %v", err)
}
// Create new Record
x := StreamingRecord{Headers: headers}
// Loop over records and add to Data field of Record struct
for _, r := range record {
x.Data = append(x.Data, r)
}
c <- x
}
return
}
func worker(jobs <-chan string, results chan<- DataFrame, resultsNames chan<- string, filePath string) {
for n := range jobs {
df := CreateDataFrame(filePath, n)
results <- df
resultsNames <- n
}
}
// Concurrently loads multiple csv files into DataFrames within the same directory.
// Returns a slice with the DataFrames in the same order as provided in the files parameter.
func LoadFrames(filePath string, files []string) ([]DataFrame, error) {
numJobs := len(files)
if numJobs <= 1 {
return nil, errors.New("LoadFrames requires at least two files")
}
jobs := make(chan string, numJobs)
results := make(chan DataFrame, numJobs)
resultsNames := make(chan string, numJobs)
// Generate workers
for i := 0; i < 4; i++ {
go worker(jobs, results, resultsNames, filePath)
}
// Load up the jobs channel
for i := 0; i < numJobs; i++ {
jobs <- files[i]
}
close(jobs) // Close jobs channel once loaded
// Map to store results
jobResults := make(map[string]DataFrame)
// Collect results and store in map
for i := 1; i <= numJobs; i++ {
jobResults[<-resultsNames] = <-results
}
var orderedResults []DataFrame
for _, f := range files {
val, ok := jobResults[f]
if !ok {
return []DataFrame{}, errors.New("An error occurred while looking up returned DataFrame in the LoadFrames function.")
}
orderedResults = append(orderedResults, val)
}
return orderedResults, nil
}
// Stack multiple DataFrames with matching headers
func Merge(dfs ...DataFrame) (DataFrame, error) {
if len(dfs) == 0 {
return DataFrame{}, nil
}
var err error
mdf := CreateNewDataFrame(dfs[0].Columns())
for _, df := range dfs {
mdf, err = mdf.ConcatFrames(&df)
if err != nil {
return DataFrame{}, err
}
}
return mdf, nil
}
// Return the values of the specified field
func (frame *DataFrame) ColumnVal(fieldName string, headers map[string]int) []string {
if _, ok := headers[fieldName]; !ok {
panic(fmt.Errorf("The provided field %s is not a valid field in the dataframe.", fieldName))
}
var fieldVals []string
records := len(frame.FrameRecords)
for i := 0; i < records; i++ {
fieldVals = append(fieldVals, frame.FrameRecords[i].Data[headers[fieldName]])
}
return fieldVals
}
// Sort the dataframe by column name
func (frame *DataFrame) Sort(columnName string) {
sort.Slice(frame.FrameRecords, func(i, j int) bool {
return frame.FrameRecords[i].Val(columnName, frame.Headers) <
frame.FrameRecords[j].Val(columnName, frame.Headers)
})
}
// Sort the dataframe by columns
func (frame *DataFrame) SortByColumns(columns []string, sortOrders []bool, dataTypes []interface{}) {
columnCount := len(columns)
sort.Slice(frame.FrameRecords, func(i, j int) bool {
record1 := frame.FrameRecords[i]
record2 := frame.FrameRecords[j]
for k := 0; k < columnCount; k++ {
val1 := record1.Val(columns[k], frame.Headers)
val2 := record2.Val(columns[k], frame.Headers)
// handle data types
switch reflect.ValueOf(dataTypes[k]).Kind() {
// int
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
intVal1, err := strconv.Atoi(val1)
if err != nil {
log.Fatalf("Error converting to int for column %s, error: %s", columns[k], err)
}
intVal2, err := strconv.Atoi(val2)
if err != nil {
log.Fatalf("Error converting to int for column %s, error: %s", columns[k], err)
}
if intVal1 != intVal2 {
if sortOrders[k] {
return intVal1 < intVal2
}
return intVal1 > intVal2
}
// float
case reflect.Float32, reflect.Float64:
floatVal1, err := strconv.ParseFloat(val1, 64)
if err != nil {
log.Fatalf("Error converting to float for column %s, error: %s", columns[k], err)
}
floatVal2, err := strconv.ParseFloat(val2, 64)
if err != nil {
log.Fatalf("Error converting to float for column %s, error: %s", columns[k], err)
}
if floatVal1 != floatVal2 {
if sortOrders[k] {
return floatVal1 < floatVal2
}
return floatVal1 > floatVal2
}
// string
case reflect.String:
if val1 != val2 {
if sortOrders[k] {
return val1 < val2
}
return val1 > val2
}
}
}
return true
})
}
// User specifies columns they want to keep from a preexisting DataFrame
func (frame DataFrame) KeepColumns(columns []string) DataFrame {
df := CreateNewDataFrame(columns)
for _, row := range frame.FrameRecords {
var newData []string
for _, column := range columns {
newData = append(newData, row.Val(column, frame.Headers))
}
df = df.AddRecord(newData)
}
return df
}
// User specifies columns they want to remove from a preexisting DataFrame
func (frame DataFrame) RemoveColumns(columns ...string) DataFrame {
approvedColumns := []string{}
for _, col := range frame.Columns() {
if !slices.Contains(columns, col) {
approvedColumns = append(approvedColumns, col)
}
}
return frame.KeepColumns(approvedColumns)
}
// Rename a specified column in the DataFrame
func (frame *DataFrame) Rename(originalColumnName, newColumnName string) error {
columns := []string{}
var columnLocation int
for k, v := range frame.Headers {
columns = append(columns, k)
if k == originalColumnName {
columnLocation = v
}
}
// Check original column name is found in DataFrame
if !slices.Contains(columns, originalColumnName) {
return errors.New("The original column name provided was not found in the DataFrame")
}
// Check new column name does not already exist
if slices.Contains(columns, newColumnName) {
return errors.New("The provided new column name already exists in the DataFrame and is not allowed")
}
// Remove original column name
delete(frame.Headers, originalColumnName)
// Add new column name
frame.Headers[newColumnName] = columnLocation
return nil
}
// Add a new record to the DataFrame
func (frame DataFrame) AddRecord(newData []string) DataFrame {
x := Record{Data: []string{}}
for _, each := range newData {
x.Data = append(x.Data, each)
}
frame.FrameRecords = append(frame.FrameRecords, x)
return frame
}
// Add a new record to the DataFrame
func (frame *DataFrame) AddRecordByReference(newData []string) {
x := Record{Data: []string{}}
for _, each := range newData {
x.Data = append(x.Data, each)
}
frame.FrameRecords = append(frame.FrameRecords, x)
}
// Provides a slice of columns in order
func (frame DataFrame) Columns() []string {
var columns []string
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
columns = append(columns, k)
}
}
}
return columns
}
// Generates a decoupled copy of an existing DataFrame.
// Changes made to either the original or new copied frame
// will not be reflected in the other.
func (frame DataFrame) Copy() DataFrame {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
df := CreateNewDataFrame(headers)
for i := 0; i < len(frame.FrameRecords); i++ {
df = df.AddRecord(frame.FrameRecords[i].Data)
}
return df
}
func (frame DataFrame) Where(fieldName, operator, value string) DataFrame {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i := 0; i < len(frame.FrameRecords); i++ {
val := frame.FrameRecords[i].Data[frame.Headers[fieldName]]
switch operator {
case "==":
if val == value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
case "!=":
if val != value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
case ">":
if val > value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
case "<":
if val < value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
case ">=":
if val >= value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
case "<=":
if val <= value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
}
return newFrame
}
// Generates a new filtered DataFrame.
// New DataFrame will be kept in same order as original.
func (frame DataFrame) Filtered(fieldName string, value ...string) DataFrame {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i := 0; i < len(frame.FrameRecords); i++ {
if slices.Contains(value, frame.FrameRecords[i].Data[frame.Headers[fieldName]]) {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
return newFrame
}
// Generated a new filtered DataFrame that in which a numerical column is either greater than or equal to
// a provided numerical value.
func (frame DataFrame) GreaterThanOrEqualTo(fieldName string, value float64) (DataFrame, error) {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i, row := range frame.FrameRecords {
valString := row.Val(fieldName, frame.Headers)
val, err := strconv.ParseFloat(valString, 64)
if err != nil {
return CreateNewDataFrame([]string{}), err
}
if val >= value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
return newFrame, nil
}
// Generated a new filtered DataFrame that in which a numerical column is either less than or equal to
// a provided numerical value.
func (frame DataFrame) LessThanOrEqualTo(fieldName string, value float64) (DataFrame, error) {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i, row := range frame.FrameRecords {
valString := row.Val(fieldName, frame.Headers)
val, err := strconv.ParseFloat(valString, 64)
if err != nil {
return CreateNewDataFrame([]string{}), err
}
if val <= value {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
return newFrame, nil
}
// Generates a new DataFrame that excludes specified instances.
// New DataFrame will be kept in same order as original.
func (frame DataFrame) Exclude(fieldName string, value ...string) DataFrame {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i := 0; i < len(frame.FrameRecords); i++ {
if !slices.Contains(value, frame.FrameRecords[i].Data[frame.Headers[fieldName]]) {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
return newFrame
}
// Generates a new filtered DataFrame with all records occuring after a specified date provided by the user.
// User must provide the date field as well as the desired date.
// Instances where record dates occur on the same date provided by the user will not be included.
// Records must occur after the specified date.
func (frame DataFrame) FilteredAfter(fieldName, desiredDate string) DataFrame {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i := 0; i < len(frame.FrameRecords); i++ {
recordDate := dateConverter(frame.FrameRecords[i].Data[frame.Headers[fieldName]])
isAfter := recordDate.After(dateConverter(desiredDate))
if isAfter {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
return newFrame
}
// Generates a new filtered DataFrame with all records occuring before a specified date provided by the user.
// User must provide the date field as well as the desired date.
// Instances where record dates occur on the same date provided by the user will not be included. Records must occur
// before the specified date.
func (frame DataFrame) FilteredBefore(fieldName, desiredDate string) DataFrame {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i := 0; i < len(frame.FrameRecords); i++ {
recordDate := dateConverter(frame.FrameRecords[i].Data[frame.Headers[fieldName]])
isBefore := recordDate.Before(dateConverter(desiredDate))
if isBefore {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
return newFrame
}
// Generates a new filtered DataFrame with all records occuring between a specified date range provided by the user.
// User must provide the date field as well as the desired date.
// Instances where record dates occur on the same date provided by the user will not be included. Records must occur
// between the specified start and end dates.
func (frame DataFrame) FilteredBetween(fieldName, startDate, endDate string) DataFrame {
headers := []string{}
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
headers = append(headers, k)
}
}
}
newFrame := CreateNewDataFrame(headers)
for i := 0; i < len(frame.FrameRecords); i++ {
recordDate := dateConverter(frame.FrameRecords[i].Data[frame.Headers[fieldName]])
isAfter := recordDate.After(dateConverter(startDate))
isBefore := recordDate.Before(dateConverter(endDate))
if isAfter && isBefore {
newFrame = newFrame.AddRecord(frame.FrameRecords[i].Data)
}
}
return newFrame
}
// Creates a new field and assigns and empty string.
func (frame *DataFrame) NewField(fieldName string) {
for i, _ := range frame.FrameRecords {
frame.FrameRecords[i].Data = append(frame.FrameRecords[i].Data, "")
}
frame.Headers[fieldName] = len(frame.Headers)
}
// Return a slice of all unique values found in a specified field.
func (frame *DataFrame) Unique(fieldName string) []string {
var results []string
for _, row := range frame.FrameRecords {
if !slices.Contains(results, row.Val(fieldName, frame.Headers)) {
results = append(results, row.Val(fieldName, frame.Headers))
}
}
return results
}
// Stack two DataFrames with matching headers.
func (frame DataFrame) ConcatFrames(dfNew *DataFrame) (DataFrame, error) {
// Check number of columns in each frame match.
if len(frame.Headers) != len(dfNew.Headers) {
return frame, errors.New("Cannot ConcatFrames as columns do not match.")
}
// Check columns in both frames are in the same order.
originalFrame := []string{}
for i := 0; i <= len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
originalFrame = append(originalFrame, k)
}
}
}
newFrame := []string{}
for i := 0; i <= len(dfNew.Headers); i++ {
for k, v := range dfNew.Headers {
if v == i {
newFrame = append(newFrame, k)
}
}
}
for i, each := range originalFrame {
if each != newFrame[i] {
return frame, errors.New("Cannot ConcatFrames as columns are not in the same order.")
}
}
// Iterate over new dataframe in order
for i := 0; i < len(dfNew.FrameRecords); i++ {
frame.FrameRecords = append(frame.FrameRecords, dfNew.FrameRecords[i])
}
return frame, nil
}
// Import all columns from right frame into left frame if no columns
// are provided by the user. Process must be done so in order.
func (frame DataFrame) Merge(dfRight *DataFrame, primaryKey string, columns ...string) {
if len(columns) == 0 {
for i := 0; i < len(dfRight.Headers); i++ {
for k, v := range dfRight.Headers {
if v == i {
columns = append(columns, k)
}
}
}
} else {
// Ensure columns user provided are all found in right frame.
for _, col := range columns {
colStatus := false
for k, _ := range dfRight.Headers {
if col == k {
colStatus = true
}
}
// Ensure there are no duplicated columns other than the primary key.
if colStatus != true {
panic("Merge Error: User provided column not found in right dataframe.")
}
}
}
// Check that no columns are duplicated between the two frames (other than primaryKey).
for _, col := range columns {
for k, _ := range frame.Headers {
if col == k && col != primaryKey {
panic("The following column is duplicated in both frames and is not the specified primary key which is not allowed: " + col)
}
}
}
// Load map indicating the location of each lookup value in right frame.
lookup := make(map[string]int)
for i, row := range dfRight.FrameRecords {
lookup[row.Val(primaryKey, dfRight.Headers)] = i
}
// Create new columns in left frame.
for _, col := range columns {
if col != primaryKey {
frame.NewField(col)
}
}
// Iterate over left frame and add new data.
for _, row := range frame.FrameRecords {
lookupVal := row.Val(primaryKey, frame.Headers)
if val, ok := lookup[lookupVal]; ok {
for _, col := range columns {
if col != primaryKey {
valToAdd := dfRight.FrameRecords[val].Data[dfRight.Headers[col]]
row.Update(col, valToAdd, frame.Headers)
}
}
}
}
}
// Performs an inner merge where all columns are consolidated between the two frames but only for records
// where the specified primary key is found in both frames.
func (frame DataFrame) InnerMerge(dfRight *DataFrame, primaryKey string) DataFrame {
var rightFrameColumns []string
for i := 0; i < len(dfRight.Headers); i++ {
for k, v := range dfRight.Headers {
if v == i {
rightFrameColumns = append(rightFrameColumns, k)
}
}
}
var leftFrameColumns []string
for i := 0; i < len(frame.Headers); i++ {
for k, v := range frame.Headers {
if v == i {
leftFrameColumns = append(leftFrameColumns, k)
}
}
}
// Ensure the specified primary key is found in both frames.
var lStatus bool
var rStatus bool
for _, col := range leftFrameColumns {
if col == primaryKey {
lStatus = true
}
}
for _, col := range rightFrameColumns {
if col == primaryKey {
rStatus = true
}
}
if !lStatus || !rStatus {
panic("The specified primary key was not found in both DataFrames.")
}
// Find position of primary key column in right frame.
var rightFramePrimaryKeyPosition int
for i, col := range rightFrameColumns {
if col == primaryKey {
rightFramePrimaryKeyPosition = i
}
}
// Check that no columns are duplicated between the two frames (other than primaryKey).
for _, col := range rightFrameColumns {
for k, _ := range frame.Headers {
if col == k && col != primaryKey {
panic("The following column is duplicated in both frames and is not the specified primary key which is not allowed: " + col)
}
}
}
// Load map indicating the location of each lookup value in right frame.
rLookup := make(map[string]int)
for i, row := range dfRight.FrameRecords {
// Only add if key hasn't already been added. This ensures the first record found in the right
// frame is what is used instead of the last if duplicates are found.
currentKey := row.Val(primaryKey, dfRight.Headers)
_, ok := rLookup[currentKey]
if !ok {
rLookup[currentKey] = i
}
}
// New DataFrame to house records found in both frames.
dfNew := CreateNewDataFrame(leftFrameColumns)
// Add right frame columns to new DataFrame.
for i, col := range rightFrameColumns {
// Skip over primary key column in right frame as it was already included in the left frame.
if i != rightFramePrimaryKeyPosition {
dfNew.NewField(col)
}
}
var approvedPrimaryKeys []string
// Create slice of specified ID's found in both frames.
for _, lRow := range frame.FrameRecords {
currentKey := lRow.Val(primaryKey, frame.Headers)
// Skip blank values as they are not allowed.
if len(currentKey) == 0 || strings.ToLower(currentKey) == "nan" || strings.ToLower(currentKey) == "null" {
continue
}
for _, rRow := range dfRight.FrameRecords {
currentRightFrameKey := rRow.Val(primaryKey, dfRight.Headers)
// Add primary key to approved list if found in right frame.
if currentRightFrameKey == currentKey {
approvedPrimaryKeys = append(approvedPrimaryKeys, currentKey)
}
}
}
// Add approved records to new DataFrame.
for i, row := range frame.FrameRecords {
currentKey := row.Val(primaryKey, frame.Headers)
if slices.Contains(approvedPrimaryKeys, currentKey) {
lData := frame.FrameRecords[i].Data
rData := dfRight.FrameRecords[rLookup[currentKey]].Data
// Add left frame data to variable.
var data []string
data = append(data, lData...)
// Add all right frame data while skipping over the primary key column.
// The primary key column is skipped as it has already been added from the left frame.
for i, d := range rData {
if i != rightFramePrimaryKeyPosition {
data = append(data, d)
}
}
dfNew = dfNew.AddRecord(data)
}
}
return dfNew
}
func (frame *DataFrame) CountRecords() int {
return len(frame.FrameRecords)
}
// Return a sum of float64 type of a numerical field.
func (frame *DataFrame) Sum(fieldName string) float64 {
var sum float64
for _, row := range frame.FrameRecords {
val, err := strconv.ParseFloat(row.Val(fieldName, frame.Headers), 64)
if err != nil {
log.Fatalf("Could Not Convert String to Float During Sum: %v", err)
}
sum += val
}
return sum
}
// Return an average of type float64 of a numerical field.
func (frame *DataFrame) Average(fieldName string) float64 {
sum := frame.Sum(fieldName)
count := frame.CountRecords()
if count == 0 {
return 0.0
}
return sum / float64(count)
}
// Return the maximum value in a numerical field.
func (frame *DataFrame) Max(fieldName string) float64 {
maximum := 0.0
for i, row := range frame.FrameRecords {
// Set the max to the first value in dataframe.