-
Notifications
You must be signed in to change notification settings - Fork 4
/
datatable.go
1586 lines (1328 loc) · 41 KB
/
datatable.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 insyra
import (
"fmt"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/HazelnutParadise/Go-Utils/asyncutil"
"github.com/HazelnutParadise/Go-Utils/conv"
)
type DataTable struct {
mu sync.Mutex
columns []*DataList
columnIndex map[string]int // 儲存字母索引與切片中的索引對應
rowNames map[string]int
creationTimestamp int64
lastModifiedTimestamp atomic.Int64
}
type IDataTable interface {
AppendCols(columns ...*DataList) *DataTable
AppendRowsFromDataList(rowsData ...*DataList) *DataTable
AppendRowsByColIndex(rowsData ...map[string]interface{}) *DataTable
AppendRowsByColName(rowsData ...map[string]interface{}) *DataTable
GetElement(rowIndex int, columnIndex string) interface{}
GetElementByNumberIndex(rowIndex int, columnIndex int) interface{}
GetCol(index string) *DataList
GetColByNumber(index int) *DataList
GetRow(index int) *DataList
UpdateElement(rowIndex int, columnIndex string, value interface{})
UpdateCol(index string, dl *DataList)
UpdateColByNumber(index int, dl *DataList)
UpdateRow(index int, dl *DataList)
SetColToRowNames(columnIndex string) *DataTable
SetRowToColNames(rowIndex int) *DataTable
FindRowsIfContains(value interface{}) []int
FindRowsIfContainsAll(values ...interface{}) []int
FindRowsIfAnyElementContainsSubstring(substring string) []int
FindRowsIfAllElementsContainSubstring(substring string) []int
FindColsIfContains(value interface{}) []string
FindColsIfContainsAll(values ...interface{}) []string
FindColsIfAnyElementContainsSubstring(substring string) []string
FindColsIfAllElementsContainSubstring(substring string) []string
DropColsByName(columnNames ...string)
DropColsByIndex(columnIndices ...string)
DropColsByNumber(columnIndices ...int)
DropColsContainStringElements()
DropColsContainNumbers()
DropColsContainNil()
DropRowsByIndex(rowIndices ...int)
DropRowsByName(rowNames ...string)
DropRowsContainStringElements()
DropRowsContainNumbers()
DropRowsContainNil()
Data(useNamesAsKeys ...bool) map[string][]interface{}
Show()
ShowTypes()
GetRowNameByIndex(index int) string
SetRowNameByIndex(index int, name string)
GetCreationTimestamp() int64
GetLastModifiedTimestamp() int64
getSortedColNames() []string
getRowNameByIndex(index int) (string, bool)
getMaxColLength() int
updateTimestamp()
// Statistics
Size() (int, int)
Count(value interface{}) int
Mean() interface{}
// Conversion
Transpose() *DataTable
// Filters
Filter(filterFunc FilterFunc) *DataTable
FilterByCustomElement(f func(value interface{}) bool) *DataTable
FilterByColIndexGreaterThan(threshold string) *DataTable
FilterByColIndexGreaterThanOrEqualTo(threshold string) *DataTable
FilterByColIndexLessThan(threshold string) *DataTable
FilterByColIndexLessThanOrEqualTo(threshold string) *DataTable
FilterByColIndexEqualTo(index string) *DataTable
FilterByColNameEqualTo(name string) *DataTable
FilterByColNameContains(substring string) *DataTable
FilterByRowNameEqualTo(name string) *DataTable
FilterByRowNameContains(substring string) *DataTable
FilterByRowIndexGreaterThan(threshold int) *DataTable
FilterByRowIndexGreaterThanOrEqualTo(threshold int) *DataTable
FilterByRowIndexLessThan(threshold int) *DataTable
FilterByRowIndexLessThanOrEqualTo(threshold int) *DataTable
FilterByRowIndexEqualTo(index int) *DataTable
// CSV
ToCSV(filePath string, setRowNamesToFirstCol bool, setColNamesToFirstRow bool) error
LoadFromCSV(filePath string, setFirstColToRowNames bool, setFirstRowToColNames bool) error
sortColsByIndex()
regenerateColIndex()
}
func NewDataTable(columns ...*DataList) *DataTable {
now := time.Now().Unix()
newTable := &DataTable{
columns: []*DataList{},
columnIndex: make(map[string]int),
rowNames: make(map[string]int),
creationTimestamp: now,
}
newTable.lastModifiedTimestamp.Store(now)
if len(columns) > 0 {
newTable.AppendCols(columns...)
}
return newTable
}
// ======================== Append ========================
// AppendCols appends columns to the DataTable, with each column represented by a DataList.
// If the columns are shorter than the existing columns, nil values will be appended to match the length.
// If the columns are longer than the existing columns, the existing columns will be extended with nil values.
func (dt *DataTable) AppendCols(columns ...*DataList) *DataTable {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
maxLength := dt.getMaxColLength()
for _, column := range columns {
columnName := generateColIndex(len(dt.columns)) // 修改這行確保按順序生成列名
column.name = safeColName(dt, column.name)
dt.columns = append(dt.columns, column)
dt.columnIndex[columnName] = len(dt.columns) - 1
if len(column.data) < maxLength {
column.data = append(column.data, make([]interface{}, maxLength-len(column.data))...)
}
LogDebug("AppendCols: Added column %s at index %d", columnName, dt.columnIndex[columnName])
}
for _, col := range dt.columns {
if len(col.data) < maxLength {
col.data = append(col.data, make([]interface{}, maxLength-len(col.data))...)
}
}
return dt
}
// AppendRowsFromDataList appends rows to the DataTable, with each row represented by a DataList.
// If the rows are shorter than the existing columns, nil values will be appended to match the length.
// If the rows are longer than the existing columns, the existing columns will be extended with nil values.
func (dt *DataTable) AppendRowsFromDataList(rowsData ...*DataList) *DataTable {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
for _, rowData := range rowsData {
maxLength := dt.getMaxColLength()
if rowData.name != "" {
srn := safeRowName(dt, rowData.name)
dt.rowNames[srn] = maxLength
}
if len(rowData.data) > len(dt.columns) {
for i := len(dt.columns); i < len(rowData.data); i++ {
newCol := newEmptyDataList(maxLength)
columnName := generateColIndex(i)
dt.columns = append(dt.columns, newCol)
dt.columnIndex[columnName] = len(dt.columns) - 1
}
}
for i, column := range dt.columns {
if i < len(rowData.data) {
column.data = append(column.data, rowData.data[i])
} else {
column.data = append(column.data, nil)
}
}
for _, column := range dt.columns {
if len(column.data) == maxLength {
column.data = append(column.data, nil)
}
}
}
return dt
}
// AppendRowsByIndex appends rows to the DataTable, with each row represented by a map of column index and value.
// If the rows are shorter than the existing columns, nil values will be appended to match the length.
// If the rows are longer than the existing columns, the existing columns will be extended with nil values.
func (dt *DataTable) AppendRowsByColIndex(rowsData ...map[string]interface{}) *DataTable {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
upperCaseRowsData := make([]map[string]interface{}, len(rowsData))
for i, rowData := range rowsData {
upperCaseRowData := make(map[string]interface{})
for colIndex, value := range rowData {
upperCaseRowData[strings.ToUpper(colIndex)] = value
}
upperCaseRowsData[i] = upperCaseRowData
}
rowsData = upperCaseRowsData
for _, rowData := range rowsData {
maxLength := dt.getMaxColLength()
// 搜集所有要處理的欄位索引(確保無論是否存在都處理)
allCols := make([]string, 0, len(rowData))
for colIndex := range rowData {
allCols = append(allCols, colIndex)
}
// 按照字母順序對欄位進行排序
sort.Strings(allCols)
// 按照排序順序處理每個欄位
for _, colIndex := range allCols {
value := rowData[colIndex]
_, exists := dt.columnIndex[colIndex]
LogDebug("AppendRowsByIndex: Handling column %s, exists: %t", colIndex, exists)
if !exists {
// 如果該欄位不存在,新增該欄位並插入字母順序位置
newCol := newEmptyDataList(maxLength)
dt.columns = append(dt.columns, newCol)
dt.columnIndex[colIndex] = len(dt.columns) - 1
LogDebug("AppendRowsByIndex: Added new column %s at index %d", colIndex, dt.columnIndex[colIndex])
// 重新排序欄位以符合字母順序
dt.sortColsByIndex()
}
dt.columns[dt.columnIndex[colIndex]].data = append(dt.columns[dt.columnIndex[colIndex]].data, value)
}
// 確保所有欄位的長度一致
for _, column := range dt.columns {
if len(column.data) <= maxLength {
column.data = append(column.data, nil)
}
}
}
return dt
}
// AppendRowsByName appends rows to the DataTable, with each row represented by a map of column name and value.
// If the rows are shorter than the existing columns, nil values will be appended to match the length.
// If the rows are longer than the existing columns, the existing columns will be extended with nil values.
func (dt *DataTable) AppendRowsByColName(rowsData ...map[string]interface{}) *DataTable {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
for _, rowData := range rowsData {
maxLength := dt.getMaxColLength()
for colName, value := range rowData {
found := false
for i := 0; i < len(dt.columns); i++ {
if dt.columns[i].name == colName {
dt.columns[i].data = append(dt.columns[i].data, value)
found = true
LogDebug("AppendRowsByName: Found column %s at index %d", colName, i)
break
}
}
if !found {
newCol := newEmptyDataList(maxLength)
newCol.name = colName
newCol.data = append(newCol.data, value)
dt.columns = append(dt.columns, newCol)
dt.columnIndex[generateColIndex(len(dt.columns)-1)] = len(dt.columns) - 1 // 更新 columnIndex
LogDebug("AppendRowsByName: Added new column %s at index %d", colName, len(dt.columns)-1)
}
}
for _, column := range dt.columns {
if len(column.data) == maxLength {
column.data = append(column.data, nil)
}
}
}
dt.regenerateColIndex()
return dt
}
// ======================== Get ========================
// GetElement returns the element at the given row and column index.
func (dt *DataTable) GetElement(rowIndex int, columnIndex string) interface{} {
dt.mu.Lock()
defer dt.mu.Unlock()
columnIndex = strings.ToUpper(columnIndex)
if colPos, exists := dt.columnIndex[columnIndex]; exists {
if rowIndex < 0 {
rowIndex = len(dt.columns[colPos].data) + rowIndex
}
if rowIndex < 0 || rowIndex >= len(dt.columns[colPos].data) {
LogWarning("DataTable.GetElement(): Row index is out of range, returning nil.")
return nil
}
return dt.columns[colPos].data[rowIndex]
}
return nil
}
func (dt *DataTable) GetElementByNumberIndex(rowIndex int, columnIndex int) interface{} {
dt.mu.Lock()
defer dt.mu.Unlock()
if rowIndex < 0 {
rowIndex = len(dt.columns[columnIndex].data) + rowIndex
}
if rowIndex < 0 || rowIndex >= len(dt.columns[columnIndex].data) {
LogWarning("DataTable.GetElementByNumberIndex(): Row index is out of range, returning nil.")
return nil
}
return dt.columns[columnIndex].data[rowIndex]
}
// GetCol returns a new DataList containing the data of the column with the given index.
func (dt *DataTable) GetCol(index string) *DataList {
dt.mu.Lock()
defer dt.mu.Unlock()
index = strings.ToUpper(index)
if colPos, exists := dt.columnIndex[index]; exists {
// 初始化新的 DataList 並分配 data 切片的大小
dl := NewDataList()
dl.data = make([]interface{}, len(dt.columns[colPos].data))
// 拷貝數據到新的 DataList
copy(dl.data, dt.columns[colPos].data)
dl.name = dt.columns[colPos].name
return dl
}
return nil
}
func (dt *DataTable) GetColByNumber(index int) *DataList {
dt.mu.Lock()
defer dt.mu.Unlock()
if index < 0 {
index = len(dt.columns) + index
}
if index < 0 || index >= len(dt.columns) {
LogWarning("DataTable.GetColByNumber(): Col index is out of range, returning nil.")
return nil
}
// 初始化新的 DataList 並分配 data 切片的大小
dl := NewDataList()
dl.data = make([]interface{}, len(dt.columns[index].data))
// 拷貝數據到新的 DataList
copy(dl.data, dt.columns[index].data)
dl.name = dt.columns[index].name
return dl
}
// GetRow returns a new DataList containing the data of the row with the given index.
func (dt *DataTable) GetRow(index int) *DataList {
dt.mu.Lock()
if index < 0 {
index = dt.getMaxColLength() + index
}
if index < 0 || index >= dt.getMaxColLength() {
LogWarning("DataTable.GetRow(): Row index is out of range, returning nil.")
return nil
}
// 初始化新的 DataList 並分配 data 切片的大小
dl := NewDataList()
dl.data = make([]interface{}, len(dt.columns))
// 拷貝數據到新的 DataList
for i, column := range dt.columns {
if index < len(column.data) {
dl.data[i] = column.data[index]
}
}
dt.mu.Unlock()
dl.name = dt.GetRowNameByIndex(index)
return dl
}
// ======================== Update ========================
// UpdateElement updates the element at the given row and column index.
func (dt *DataTable) UpdateElement(rowIndex int, columnIndex string, value interface{}) {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
dt.regenerateColIndex()
columnIndex = strings.ToUpper(columnIndex)
if colPos, exists := dt.columnIndex[columnIndex]; exists {
if rowIndex < 0 {
rowIndex = len(dt.columns[colPos].data) + rowIndex
}
if rowIndex < 0 || rowIndex >= len(dt.columns[colPos].data) {
LogWarning("DataTable.UpdateElement(): Row index is out of range, returning.")
return
}
dt.columns[colPos].data[rowIndex] = value
} else {
LogWarning("DataTable.UpdateElement(): Col index does not exist, returning.")
}
}
// UpdateCol updates the column with the given index.
func (dt *DataTable) UpdateCol(index string, dl *DataList) {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
dt.regenerateColIndex()
index = strings.ToUpper(index)
if colPos, exists := dt.columnIndex[index]; exists {
dt.columns[colPos] = dl
} else {
LogWarning("DataTable.UpdateCol(): Col index does not exist, returning.")
}
}
// UpdateColByNumber updates the column at the given index.
func (dt *DataTable) UpdateColByNumber(index int, dl *DataList) {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
if index < 0 {
index = len(dt.columns) + index
}
if index < 0 || index >= len(dt.columns) {
LogWarning("DataTable.UpdateColByNumber(): Index out of bounds")
return
}
dt.columns[index] = dl
dt.columnIndex[generateColIndex(index)] = index
}
// UpdateRow updates the row at the given index.
func (dt *DataTable) UpdateRow(index int, dl *DataList) {
dt.mu.Lock()
defer dt.mu.Unlock()
if index < 0 || index >= dt.getMaxColLength() {
LogWarning("DataTable.UpdateRow(): Index out of bounds")
return
}
if len(dl.data) > len(dt.columns) {
LogWarning("DataTable.UpdateRow(): DataList has more elements than DataTable columns, returning.")
return
}
// 更新 DataTable 中對應行的資料
for i := 0; i < len(dl.data); i++ {
dt.columns[i].data[index] = dl.data[i]
}
// 更新行名
if dl.name != "" {
for rowName, rowIndex := range dt.rowNames {
if rowIndex == index {
delete(dt.rowNames, rowName)
break
}
}
srn := safeRowName(dt, dl.name)
dt.rowNames[srn] = index
}
go dt.updateTimestamp()
}
// ======================== Set ========================
// SetColToRowNames sets the row names to the values of the specified column and drops the column.
func (dt *DataTable) SetColToRowNames(columnIndex string) *DataTable {
columnIndex = strings.ToUpper(columnIndex)
column := dt.GetCol(columnIndex)
for i, value := range column.data {
if value != nil {
rowName := safeRowName(dt, conv.ToString(value))
dt.rowNames[rowName] = i
}
}
dt.DropColsByIndex(columnIndex)
dt.regenerateColIndex()
go dt.updateTimestamp()
return dt
}
// SetRowToColNames sets the column names to the values of the specified row and drops the row.
func (dt *DataTable) SetRowToColNames(rowIndex int) *DataTable {
row := dt.GetRow(rowIndex)
for i, value := range row.data {
if value != nil {
columnName := safeColName(dt, conv.ToString(value))
dt.columns[i].name = columnName
}
}
dt.DropRowsByIndex(rowIndex)
go dt.updateTimestamp()
return dt
}
// ======================== Find ========================
// FindRowsIfContains returns the indices of rows that contain the given element.
func (dt *DataTable) FindRowsIfContains(value interface{}) []int {
dt.mu.Lock()
defer dt.mu.Unlock()
// 使用 map 來確保行索引唯一性
indexMap := make(map[int]struct{})
for _, column := range dt.columns {
// 找到該列中包含 value 的所有行索引
indexes := column.FindAll(value)
for _, index := range indexes {
indexMap[index] = struct{}{}
}
}
// 將唯一的行索引轉換為 slice
var result []int
for index := range indexMap {
result = append(result, index)
}
// 排序結果以保證順序
sort.Ints(result)
return result
}
// FindRowsIfContainsAll returns the indices of rows that contain all the given elements.
func (dt *DataTable) FindRowsIfContainsAll(values ...interface{}) []int {
dt.mu.Lock()
defer dt.mu.Unlock()
var result []int
// 檢查每一行是否包含所有指定的值
for rowIndex := 0; rowIndex < dt.getMaxColLength(); rowIndex++ {
foundAll := true
// 檢查該行中的所有列是否包含指定的值
for _, value := range values {
found := false
for _, column := range dt.columns {
if rowIndex < len(column.data) && column.data[rowIndex] == value {
found = true
break
}
}
if !found {
foundAll = false
break
}
}
// 如果該行包含所有指定的值,則將其索引添加到結果中
if foundAll {
result = append(result, rowIndex)
}
}
return result
}
// FindRowsIfAnyElementContainsSubstring returns the indices of rows that contain at least one element that contains the given substring.
func (dt *DataTable) FindRowsIfAnyElementContainsSubstring(substring string) []int {
dt.mu.Lock()
defer dt.mu.Unlock()
var matchingRows []int
for rowIndex := 0; rowIndex < dt.getMaxColLength(); rowIndex++ {
for _, col := range dt.columns {
if rowIndex < len(col.data) {
if value, ok := col.data[rowIndex].(string); ok {
if containsSubstring(value, substring) {
matchingRows = append(matchingRows, rowIndex)
break // 一旦找到匹配的元素,跳出內層循環檢查下一行
}
}
}
}
}
return matchingRows
}
// FindRowsIfAllElementsContainSubstring returns the indices of rows that contain all elements that contain the given substring.
func (dt *DataTable) FindRowsIfAllElementsContainSubstring(substring string) []int {
dt.mu.Lock()
defer dt.mu.Unlock()
var matchingRows []int
for rowIndex := 0; rowIndex < dt.getMaxColLength(); rowIndex++ {
foundAll := true
for _, col := range dt.columns {
if rowIndex < len(col.data) {
if value, ok := col.data[rowIndex].(string); ok {
if !containsSubstring(value, substring) {
foundAll = false
break
}
}
}
}
if foundAll {
matchingRows = append(matchingRows, rowIndex)
}
}
return matchingRows
}
// FindColsIfContains returns the indices of columns that contain the given element.
func (dt *DataTable) FindColsIfContains(value interface{}) []string {
dt.mu.Lock()
defer dt.mu.Unlock()
var result []string
for colName, colPos := range dt.columnIndex {
if dt.columns[colPos].FindFirst(value) != nil {
result = append(result, colName)
}
}
return result
}
// FindColsIfContainsAll returns the indices of columns that contain all the given elements.
func (dt *DataTable) FindColsIfContainsAll(values ...interface{}) []string {
dt.mu.Lock()
defer dt.mu.Unlock()
var result []string
for colName, colPos := range dt.columnIndex {
foundAll := true
for _, value := range values {
if dt.columns[colPos].FindFirst(value) == nil {
foundAll = false
break
}
}
if foundAll {
result = append(result, colName)
}
}
return result
}
// FindColsIfAnyElementContainsSubstring returns the indices of columns that contain at least one element that contains the given substring.
func (dt *DataTable) FindColsIfAnyElementContainsSubstring(substring string) []string {
dt.mu.Lock()
defer dt.mu.Unlock()
var result []string
for colName, colPos := range dt.columnIndex {
found := false
for _, value := range dt.columns[colPos].data {
if value != nil {
if str, ok := value.(string); ok && containsSubstring(str, substring) {
found = true
break
}
}
}
if found {
result = append(result, colName)
}
}
return result
}
// FindColsIfAllElementsContainSubstring returns the indices of columns that contain all elements that contain the given substring.
func (dt *DataTable) FindColsIfAllElementsContainSubstring(substring string) []string {
dt.mu.Lock()
defer dt.mu.Unlock()
var result []string
for colName, colPos := range dt.columnIndex {
foundAll := true
for _, value := range dt.columns[colPos].data {
if value != nil {
if str, ok := value.(string); ok && !containsSubstring(str, substring) {
foundAll = false
break
}
}
}
if foundAll {
result = append(result, colName)
}
}
return result
}
// ======================== Drop ========================
// DropColsByName drops columns by their names.
func (dt *DataTable) DropColsByName(columnNames ...string) {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
for _, name := range columnNames {
for colName, colPos := range dt.columnIndex {
if dt.columns[colPos].name == name {
// 刪除對應的列
dt.columns = append(dt.columns[:colPos], dt.columns[colPos+1:]...)
delete(dt.columnIndex, colName)
// 更新剩餘列的索引
for i := colPos; i < len(dt.columns); i++ {
newColName := generateColIndex(i)
dt.columnIndex[newColName] = i
}
break
}
}
}
dt.regenerateColIndex()
}
// DropColsByIndex drops columns by their index names.
func (dt *DataTable) DropColsByIndex(columnIndices ...string) {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
for _, index := range columnIndices {
index = strings.ToUpper(index)
colPos, exists := dt.columnIndex[index]
if exists {
// 刪除對應的列
dt.columns = append(dt.columns[:colPos], dt.columns[colPos+1:]...)
delete(dt.columnIndex, index)
// 更新剩餘列的索引
for i := colPos; i < len(dt.columns); i++ {
newColIndex := generateColIndex(i)
dt.columnIndex[newColIndex] = i
}
}
}
dt.regenerateColIndex()
}
// DropColsByNumber drops columns by their number.
func (dt *DataTable) DropColsByNumber(columnIndices ...int) {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
// 從大到小排序,防止刪除後索引變動
sort.Sort(sort.Reverse(sort.IntSlice(columnIndices)))
for _, index := range columnIndices {
if index >= 0 && index < len(dt.columns) {
dt.columns = append(dt.columns[:index], dt.columns[index+1:]...)
delete(dt.columnIndex, generateColIndex(index))
}
}
dt.regenerateColIndex()
}
// DropColsContainStringElements drops columns that contain string elements.
func (dt *DataTable) DropColsContainStringElements() {
dt.mu.Lock()
defer dt.mu.Unlock()
columnsToDelete := make([]int, 0)
// 找出包含字串元素的列索引
for colIndex, column := range dt.columns {
containsString := false
for _, value := range column.data {
if _, ok := value.(string); ok {
containsString = true
break
}
}
if containsString {
columnsToDelete = append(columnsToDelete, colIndex)
}
}
// 反向刪除列,以避免索引錯誤
for i := len(columnsToDelete) - 1; i >= 0; i-- {
colIndex := columnsToDelete[i]
dt.columns = append(dt.columns[:colIndex], dt.columns[colIndex+1:]...)
delete(dt.columnIndex, generateColIndex(colIndex))
}
dt.regenerateColIndex()
go dt.updateTimestamp()
}
// DropColsContainNumbers drops columns that contain number elements.
func (dt *DataTable) DropColsContainNumbers() {
dt.mu.Lock()
defer dt.mu.Unlock()
columnsToDelete := make([]int, 0)
for colIndex, column := range dt.columns {
containsNumber := false
for _, value := range column.data {
if _, isNumber := value.(int); isNumber {
containsNumber = true
break
} else if _, isNumber := value.(float64); isNumber {
containsNumber = true
break
}
}
if containsNumber {
columnsToDelete = append(columnsToDelete, colIndex)
}
}
for i := len(columnsToDelete) - 1; i >= 0; i-- {
colIndex := columnsToDelete[i]
dt.columns = append(dt.columns[:colIndex], dt.columns[colIndex+1:]...)
delete(dt.columnIndex, generateColIndex(colIndex))
}
dt.regenerateColIndex()
go dt.updateTimestamp()
}
// DropColsContainNil drops columns that contain nil elements.
func (dt *DataTable) DropColsContainNil() {
dt.mu.Lock()
defer dt.mu.Unlock()
columnsToDelete := make([]int, 0)
for colIndex, column := range dt.columns {
containsNil := false
for _, value := range column.data {
if value == nil {
containsNil = true
break
}
}
if containsNil {
columnsToDelete = append(columnsToDelete, colIndex)
}
}
for i := len(columnsToDelete) - 1; i >= 0; i-- {
colIndex := columnsToDelete[i]
dt.columns = append(dt.columns[:colIndex], dt.columns[colIndex+1:]...)
delete(dt.columnIndex, generateColIndex(colIndex))
}
dt.regenerateColIndex()
go dt.updateTimestamp()
}
// DropRowsByIndex drops rows by their indices.
func (dt *DataTable) DropRowsByIndex(rowIndices ...int) {
dt.mu.Lock()
defer func() {
dt.mu.Unlock()
go dt.updateTimestamp()
}()
sort.Ints(rowIndices) // 確保從最小索引開始刪除
for i, rowIndex := range rowIndices {
adjustedIndex := rowIndex - i // 因為每刪除一行,後續的行索引會變動
for _, column := range dt.columns {
if adjustedIndex >= 0 && adjustedIndex < len(column.data) {
column.data = append(column.data[:adjustedIndex], column.data[adjustedIndex+1:]...)
}
}
// 如果該行有名稱,也從 rowNames 中刪除
for rowName, index := range dt.rowNames {
if index == rowIndex {
delete(dt.rowNames, rowName)
break
}
}
}
}
// DropRowsByName drops rows by their names.
func (dt *DataTable) DropRowsByName(rowNames ...string) {
dt.mu.Lock()
defer dt.mu.Unlock()
for _, rowName := range rowNames {
rowIndex, exists := dt.rowNames[rowName]
if !exists {
LogWarning(fmt.Sprintf("Row name '%s' does not exist.", rowName))
continue
}
// 移除所有列中對應行索引的資料
for _, column := range dt.columns {
if rowIndex < len(column.data) {
column.data = append(column.data[:rowIndex], column.data[rowIndex+1:]...)
}
}
// 移除行名索引
delete(dt.rowNames, rowName)
// 更新所有行名索引,以反映行被刪除後的變化
for name, idx := range dt.rowNames {
if idx > rowIndex {
dt.rowNames[name] = idx - 1
}
}
}
go dt.updateTimestamp()
}