-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgroupby.go
61 lines (53 loc) · 1.66 KB
/
groupby.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
package gambas
// GroupBy type is a intermediary struct that is created after running DataFrame.GroupBy().
// It holds the necessary data for applying operations such as GroupBy.Agg().
type GroupBy struct {
dataFrame *DataFrame
colIndMap map[string][]interface{}
colTuples [][]interface{}
colTuplesLabels []string
}
// Agg aggregates data in the GroupBy object using the given aggFunc.
func (gb *GroupBy) Agg(targetCol []string, aggFunc StatsFunc) (DataFrame, error) {
filtered, err := gb.dataFrame.LocCols(targetCol...)
if err != nil {
return DataFrame{}, err
}
newDfData := make([][]interface{}, len(gb.colTuples[0]))
for _, colTuple := range gb.colTuples {
for j, col := range colTuple {
newDfData[j] = append(newDfData[j], col)
}
}
results := make([]interface{}, 0)
for _, ser := range filtered.series {
for i, colTuple := range gb.colTuples {
colTupleIndex := Index{i, colTuple}
key, err := colTupleIndex.hashKeyValueOnly()
if err != nil {
return DataFrame{}, err
}
indexForData := gb.colIndMap[*key]
data := make([]interface{}, 0)
for _, id := range indexForData {
d, err := ser.IAt(id.(int))
if err != nil {
return DataFrame{}, err
}
data = append(data, d)
}
result := aggFunc(data)
results = append(results, result.Result)
}
}
newDfData = append(newDfData, results)
newDfColumns := make([]string, 0)
newDfColumns = append(newDfColumns, gb.colTuplesLabels...)
newDfColumns = append(newDfColumns, filtered.columns...)
newDf, err := NewDataFrame(newDfData, newDfColumns, gb.colTuplesLabels)
if err != nil {
return DataFrame{}, err
}
newDf.SortByIndex(true)
return newDf, nil
}