-
-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathgroupby.ts
More file actions
672 lines (624 loc) · 18.3 KB
/
groupby.ts
File metadata and controls
672 lines (624 loc) · 18.3 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
/**
* @license
* Copyright 2022 JsData. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ==========================================================================
*/
import DataFrame from "../core/frame"
import { ArrayType1D, ArrayType2D } from "../shared/types"
import { variance, std, median, mode } from 'mathjs';
import concat from "../transformers/concat"
import Series from "../core/series";
/**
* The class performs all groupby operation on a dataframe
* involving all aggregate funciton
* @param {colDict} colDict Object of unique keys in the group by column
* @param {keyCol} keyCol Array contains the column names
* @param {data} Array the dataframe data
* @param {columnName} Array of all column name in the dataframe.
* @param {colDtype} Array columns dtype
*/
export default class Groupby {
colDict: { [key: string ]: {} } = {}
keyCol: ArrayType1D
data?: ArrayType2D | null
columnName: ArrayType1D
colDtype: ArrayType1D
colIndex: ArrayType1D
groupDict?: any
groupColNames?: Array<string>
keyToValue: {
[key: string] : ArrayType1D
} = {}
constructor(keyCol: ArrayType1D, data: ArrayType2D | null, columnName: ArrayType1D, colDtype:ArrayType1D, colIndex: ArrayType1D) {
this.keyCol = keyCol;
this.data = data;
this.columnName = columnName;
//this.dataTensors = {}; //store the tensor version of the groupby data
this.colDtype = colDtype;
this.colIndex = colIndex
}
/**
* Generate group object data needed for group operations
* let data = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 20, 30, 40 ], [ 39, 89, 78 ] ];
* let cols = [ "A", "B", "C" ];
* let df = new dfd.DataFrame(data, { columns: cols });
* let groupDf = df.groupby([ "A" ]);
* The following internal object is generated and save to this.colDict
* {
* '1': { A: [ 1 ], B: [ 2 ], C: [ 3 ] },
* '4': { A: [ 4 ], B: [ 5 ], C: [ 6 ] },
* '20': { A: [ 20 ], B: [ 30 ], C: [ 40 ] },
* '39': { A: [ 39 ], B: [ 89 ], C: [ 78 ] }
* }
* Since for groupby using more than one columns is index via '-'
* e.g for df.groupby(['A','B'])
* the result will look like this
* {
* '1-2': {A: [ 1 ], B: [ 2 ], C: [ 3 ]},
* '4-5': {A: [ 4 ], B: [ 5 ], C: [ 6 ]}
* }
* but in doing analysis on a specific column like this
* df.groupby(['A','B']).col(['C'])
* will have the following set of internal result
* {
* '1-2': { C: [ 3 ]},
* '4-5': {C: [ 6 ]}
* }
* In building our multindex type of DataFrame for this data,
* we've somehow loose track of value for column A and B.
* This could actually be generated by using split('-') on the object keys
* e.g '1-2'.split('-') will give us the value for A and B.
* But we might have weird case scenerio where A and B value has '-`
* e.g
* {
* '1--2-': { C: [ 3 ]},
* '4--5-': {C: [ 6 ]}
* }
* using `.split('-') might not work well
* Hence we create a key-value `keyToValue` object to store index and their
* associated value
* NOTE: In the previous implementation we made use of Graph representation
* for the group by data and Depth First search (DFS). But we decided to use key-value
* object in javascript as an hashmap to reduce search time compared to using Grpah and DFS
*/
group(): Groupby{
const self = this
let keyToValue:{
[key: string] : ArrayType1D
} = {}
const group = this.data?.reduce((prev: any, current)=>{
let indexes= []
for(let i in self.colIndex) {
let index = self.colIndex[i] as number
indexes.push(current[index])
}
let index = indexes.join('-')
if(!keyToValue[index]) {
keyToValue[index] = indexes
}
if(prev[index]) {
let data = prev[index]
for (let i in self.columnName) {
let colName = self.columnName[i] as string
data[colName].push(current[i])
}
} else {
prev[index] = {}
for (let i in self.columnName) {
let colName = self.columnName[i] as string
prev[index][colName] = [current[i]]
}
}
return prev
}, {})
this.colDict = group
this.keyToValue = keyToValue
return this
}
/**
* Generate new internal groupby data
* group = df.groupby(['A', 'B']).col('C')
* This filter the colDict property as generated by `.group()`
* it filter each group to contain only column `C` in their internal object
* e.g
* {
* '1-2': {A: [ 1 ], B: [ 2 ], C: [ 3 ]},
* '4-5': {A: [ 4 ], B: [ 5 ], C: [ 6 ]}
* }
* to
* {
* '1-2': { C: [ 3 ]},
* '4-5': {C: [ 6 ]}
* }
* @param colNames column names
* @return Groupby
*/
col(colNames: ArrayType1D | undefined): Groupby {
if (typeof colNames === "undefined") {
colNames = this.columnName.filter((_, index)=>{
return !this.colIndex.includes(index)
})
}
let self = this
colNames.forEach((val) => {
if (!self.columnName.includes(val))
throw new Error(`Column ${val} does not exist in groups`)
})
let colDict: { [key: string ]: {} } = {...this.colDict}
for(let [key, values] of Object.entries(colDict)) {
let c: { [key: string ]: [] } = {}
let keyVal: any = {...values}
for(let colKey in colNames) {
let colName = colNames[colKey] as string
c[colName] = keyVal[colName]
}
colDict[key] = c
}
const gp = new Groupby(
this.keyCol,
null,
this.columnName,
this.colDtype,
this.colIndex
)
gp.colDict = colDict
gp.groupColNames = colNames as Array<string>
gp.keyToValue = this.keyToValue
return gp
}
/**
* Perform all groupby arithmetic operations
* In the previous implementation all groups data are
* stord as DataFrame, which involve lot of memory usage
* Hence each groups are just pure javascrit object
* and all arithmetic operation is done directly on javascript
* arrays.
* e.g
* using this internal data
* {
* '1-2': {A: [ 1,3 ], B: [ 2,5 ], C: [ 3, 5 ]},
* '4-5': {A: [ 4,1 ], B: [ 5,0 ], C: [ 6, 12 ]}
* }
* 1) using groupby(['A', 'B']).arithmetic("mean")
* result: * {
* '1-2': {A_mean: [ 2 ], B_mean: [ 3.5 ], C_mean: [ 4 ]},
* '4-5': {A_mean: [ 2.5 ], B: [ 2.5 ], C_mean: [ 9 ]}
* }
* 2) .arithmetic({
* A: 'mean',
* B: 'sum',
* C: 'min'
* })
* result:
* {
* '1-2': {A_mean: [ 2 ], B_sum: [ 7 ], C_min: [ 3 ]},
* '4-5': {A_mean: [ 2.5 ], B_sum: [ 5 ], C_min: [ 6 ]}
* }
* 3) .arithmetic({
* A: 'mean',
* B: 'sum',
* C: ['min', 'max']
* })
* result:
* {
* '1-2': {A_mean: [ 2 ], B_sum: [ 7 ], C_min: [ 3 ], C_max: [5]},
* '4-5': {A_mean: [ 2.5 ], B_sum: [ 5 ], C_min: [ 6 ], C_max: [12]}
* }
* @param operation
*/
private arithemetic(operation: {[key: string] : Array<string> | string} | string): { [key: string ]: {} } {
const opsName = [ "mean", "sum", "count", "mode", "std", "var", "cumsum", "cumprod",
"cummax", "cummin", "median" , "min", "max", "countdistinct"];
if (typeof operation === "string" ) {
if (!opsName.includes(operation)) {
throw new Error(`group operation: ${operation} is not valid`)
}
} else {
Object.keys(operation).forEach((key)=>{
let ops = operation[key]
if(Array.isArray(ops)) {
for(let op of ops) {
if (!opsName.includes(op)) {
throw new Error(`group operation: ${op} for column ${key} is not valid`)
}
}
} else {
if (!opsName.includes(ops)) {
throw new Error(`group operation: ${ops} for column ${key} is not valid`)
}
}
})
}
let colDict: { [key: string ]: {} } = {...this.colDict}
for(const [key, values] of Object.entries(colDict)) {
let colVal: { [key: string ]: Array<number> } = {}
let keyVal: any = {...values}
let groupColNames: Array<string> = this.groupColNames as Array<string>
for(let colKey=0; colKey < groupColNames.length; colKey++) {
let colName = groupColNames[colKey]
let colIndex = this.columnName.indexOf(colName)
let colDtype = this.colDtype[colIndex]
let operationVal = (typeof operation === "string") ? operation : operation[colName]
if (colDtype === "string" && operationVal !== "count") throw new Error(`Can't perform math operation on column ${colName}`)
if (typeof operation === "string") {
let colName2 = `${colName}_${operation}`
colVal[colName2] = this.groupMathLog(keyVal[colName], operation)
}
else {
if(Array.isArray(operation[colName])) {
for(let ops of operation[colName]) {
let colName2 = `${colName}_${ops}`
colVal[colName2] = this.groupMathLog(keyVal[colName],ops)
}
} else {
let ops: string = operation[colName] as string
let colName2 = `${colName}_${ops}`
colVal[colName2] = this.groupMathLog(keyVal[colName], ops)
}
}
}
colDict[key] = colVal
}
return colDict
}
/**
* Peform all arithmetic logic
* @param colVal
* @param ops
*/
private groupMathLog(colVal: Array<number>, ops: string): Array<number>{
let data = []
switch(ops) {
case "max":
let max = colVal.reduce((prev, curr)=> {
if (prev > curr) {
return prev
}
return curr
})
data.push(max)
break;
case "min":
let min = colVal.reduce((prev, curr)=> {
if (prev < curr) {
return prev
}
return curr
})
data.push(min)
break;
case "sum":
let sum = colVal.reduce((prev, curr)=> {
return prev + curr
})
data.push(sum)
break;
case "count":
data.push(colVal.length)
break;
case "mean":
let sumMean = colVal.reduce((prev, curr)=> {
return prev + curr
})
data.push(sumMean / colVal.length)
break;
case "std":
data.push(std(colVal))
break;
case "var":
data.push(variance(colVal))
break;
case "median":
data.push(median(colVal))
break;
case "mode":
data.push(mode(colVal))
break;
case "cumsum":
colVal.reduce((prev, curr) => {
let sum = prev + curr
data.push(sum)
return sum
}, 0)
break;
case "cummin":
data = [colVal[0]]
colVal.slice(1,).reduce((prev, curr)=>{
if (prev < curr) {
data.push(prev)
return prev
}
data.push(curr)
return curr
}, data[0])
break;
case "cummax":
data = [colVal[0]]
colVal.slice(1,).reduce((prev, curr)=> {
if (prev > curr) {
data.push(prev)
return prev
}
data.push(curr)
return curr
}, data[0])
break;
case "cumprod":
colVal.reduce((prev, curr) => {
let sum = prev * curr
data.push(sum)
return sum
}, 1)
break;
case "countdistinct":
data.push(new Set(colVal).size);
break;
}
return data
}
/**
* Takes in internal groupby internal data and convert
* them to a single data frame.
* @param colDict
*/
private toDataFrame(colDict: { [key: string ]: {} }): DataFrame {
let data: { [key: string ]: ArrayType1D } = {}
for(let key of this.colKeyDict(colDict)) {
let value = colDict[key]
let keyDict: { [key: string ]: ArrayType1D } = {}
let oneValue = Object.values(value)[0] as ArrayType1D
let valueLen = oneValue.length
for(let key1 in this.keyCol) {
let keyName = this.keyCol[key1] as string
let keyValue = this.keyToValue[key][key1]
keyDict[keyName] = Array(valueLen).fill(keyValue)
}
let combine: { [key: string ]: ArrayType1D } = {...keyDict, ...value}
if(Object.keys(data).length < 1) {
data = combine
} else {
for(let dataKey of Object.keys(data)) {
let dataValue = combine[dataKey] as ArrayType1D
data[dataKey] = [...data[dataKey], ...dataValue]
}
}
}
return new DataFrame(data)
}
private operations(ops: string): DataFrame {
if (!this.groupColNames) {
let colGroup = this.col(undefined)
let colDict = colGroup.arithemetic(ops)
let df = colGroup.toDataFrame(colDict)
return df
}
let colDict = this.arithemetic(ops)
let df = this.toDataFrame(colDict)
return df
}
/**
* Obtain the count for each group
* @returns DataFrame
*
*/
count(): DataFrame {
return this.operations("count")
}
/**
* Obtain the sum of columns for each group
* @returns DataFrame
*
*/
sum(): DataFrame{
return this.operations("sum")
}
/**
* Obtain the standard deviation of columns for each group
* @returns DataFrame
*/
std(): DataFrame{
return this.operations("std")
}
/**
* Obtain the variance of columns for each group
* @returns DataFrame
*/
var(): DataFrame{
return this.operations("var")
}
/**
* Obtain the mean of columns for each group
* @returns DataFrame
*/
mean(): DataFrame{
return this.operations("mean")
}
/**
* Obtain the cumsum of columns for each group
* @returns DataFrame
*
*/
cumSum(): DataFrame{
return this.operations("cumsum")
}
/**
* Obtain the cummax of columns for each group
* @returns DataFrame
*/
cumMax(): DataFrame{
return this.operations("cummax")
}
/**
* Obtain the cumprod of columns for each group
* @returns DataFrame
*/
cumProd(): DataFrame{
return this.operations("cumprod")
}
/**
* Obtain the cummin of columns for each group
* @returns DataFrame
*/
cumMin(): DataFrame{
return this.operations("cummin")
}
/**
* Obtain the max value of columns for each group
* @returns DataFrame
*
*/
max(): DataFrame{
return this.operations("max")
}
/**
* Obtain the min of columns for each group
* @returns DataFrame
*/
min(): DataFrame{
return this.operations("min")
}
/**
* Obtain the distinct number of columns for each group
* @returns DataFrame
*/
countDistinct(): DataFrame{
return this.operations("countdistinct")
}
/**
* Obtain a specific group
* @param keys Array<string | number>
* @returns DataFrame
*/
getGroup(keys: Array<string | number>): DataFrame {
let dictKey = keys.join("-")
let colDict: { [key: string ]: {} } = {}
colDict[dictKey] = {...this.colDict[dictKey]}
return this.toDataFrame(colDict)
}
/**
* Perform aggregation on all groups
* @param ops
* @returns DataFrame
*/
agg(ops: { [key: string ]: Array<string> | string }): DataFrame {
let columns = Object.keys(ops);
let col_gp = this.col(columns);
let data = col_gp.arithemetic(ops);
let df = col_gp.toDataFrame(data);
return df;
}
/**
* Apply custom aggregator function
* to each group
* @param callable
* @returns DataFrame
* @example
* let grp = df.groupby(['A'])
* grp.apply((x) => x.count())
*/
apply(callable: (x: DataFrame)=> DataFrame | Series ): DataFrame {
let colDict: { [key: string ]: DataFrame | Series } = {}
for(const key of this.colKeyDict(this.colDict)) {
let valDataframe = new DataFrame(this.colDict[key])
colDict[key] = callable(valDataframe)
}
return this.concatGroups(colDict)
}
private concatGroups(colDict: {[key: string]: DataFrame | Series}): DataFrame {
let data: Array<DataFrame | Series> = []
for(const [key, values] of Object.entries(colDict)) {
let copyDf: DataFrame;
if (values instanceof DataFrame) {
copyDf = values.copy()
}
else {
let columns = values.index as string[]
columns = columns.length > 1 ? columns : ['applyOps']
copyDf = new DataFrame([values.values], {columns: columns })
}
let len = copyDf.shape[0]
let key1: any;
for(key1 in this.keyCol){
let keyName = this.keyCol[key1] as string
let keyValue = this.keyToValue[key][key1]
let dfValue = Array(len).fill(keyValue)
let atIndex: number = parseInt(key1)
if (this.groupColNames) {
copyDf.addColumn(keyName, dfValue, {inplace: true, atIndex: atIndex })
}
else {
copyDf.addColumn(`${keyName}_Group`, dfValue, {inplace: true, atIndex: atIndex })
}
}
data.push(copyDf)
}
return concat({dfList: data, axis:0}) as DataFrame
}
/**
* obtain the total number of groups
* @returns number
*/
get ngroups(): number{
let keys = Object.keys(this.colDict)
return keys.length
}
/**
* obtaind the internal group data
* @returns {[keys: string]: {}}
*/
get groups(): {[keys: string]: {}}{
return this.colDict
}
/**
* Obtain the first row of each group
* @returns DataFrame
*/
first(): DataFrame{
return this.apply((x)=>{
return x.head(1)
})
}
/**
* Obtain the last row of each group
* @returns DataFrame
*/
last(): DataFrame {
return this.apply((x)=>{
return x.tail(1)
})
}
/**
* Obtains the dataframe se of each groups
* @returns DataFrame
*/
size(): DataFrame {
return this.apply((x)=>{
return new Series([x.shape[0]])
})
}
private colKeyDict(colDict: { [key: string ]: {} }): string[]{
let keyDict :{ [key: string ]: string[] } = {}
for(let key of Object.keys(colDict)) {
let firstKey = key.split("-")[0]
if (firstKey in keyDict) {
keyDict[firstKey].push(key)
}
else {
keyDict[firstKey] = [key]
}
}
let keys = []
for(let key of Object.keys(keyDict)) {
keys.push(...keyDict[key])
}
return keys
}
}