-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataFrame.js
1858 lines (1687 loc) · 57.6 KB
/
DataFrame.js
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
/* eslint-disable no-nested-ternary,max-lines,complexity */
/**
* TODO document cum ops
* TODO replace is broken
* TODO binarizer
* TODO document imports
* TODO document matrix ops
* TODO document add, mul, div, sub
* TODO document opts, printing presets
* TODO document examples of matrix ops, aggs, functs
* TODO calculate the *base* size of each column (pointers are 8B)
*/
const util = require('util');
const { join, resolve, dirname } = require('path');
const {
readdirSync,
readFileSync,
existsSync,
writeFileSync,
statSync
} = require('fs');
const request = require('sync-request');
const parseCSV = require('csv-parse/lib/sync');
const Column = require('./Column');
const { randInt } = require('./rand');
const {
fmtFloat,
fmtFloatSI,
dtypeRegex,
isNumber,
isString,
isRegExp,
isURL,
isMap,
isSameType,
isGenerator,
isObject,
walkFiles,
isFunction,
transpose
} = require('./utils');
const log = require('./log');
const opts = require('./opts');
const {
PROGRAMMER_PRINTING,
DEFAULT_PRINTING,
MINIMAL_PRINTING
} = require('./presets');
class DataFrame {
/**
* @param {DataFrame|GeneratorFunction|!Object<string|number,number|string|string[]|number[]|ColStr|ColNum|TypedArray>|Array<Array<number|string>>|Array<TypedArray|number[]|string[]|ColStr|ColNum>|!Map<String,number|string|number[]|string[]>} data
* @param {string} [what]
* @param {string[]|?ColStr} [colNames] labels for every column (#cols === #labels)
* @param {?ArrayLike<?DType|'s'>} [dtypes]
*/
constructor(data = [], what = '', colNames = null, dtypes = null) {
const prefix = `${this.constructor.name}.constructor()`;
const logIt = (lvl, msg) => log[lvl](`${prefix} ${msg}`);
const warn = (msg) => logIt('warn', msg);
const info = (msg) => logIt('info', msg);
const debug = (msg) => logIt('debug', msg);
if (what.toLowerCase() !== what) {
debug(`lowercasing "${what}"`);
return new DataFrame(data, what.toLowerCase(), colNames, dtypes);
// another data frame, shallow copy it
} else if (what === 'df') {
info(`data is another ${this.constructor.name}, making a shallow copy`);
return new DataFrame(
[...data.cols],
'cols',
[...data.colNames],
data.dtypes,
);
} else if (isSameType(this, data)) {
info(`detected ${this.constructor.name}`);
return new DataFrame(data, 'df', colNames, dtypes);
} else if (isString(data)) {
if (what.startsWith('url')) {
info(`GET ${data}`);
let newWhat;
if (what === 'url') {
newWhat = data.search(/\.json$/i) >= 0 ? 'json' : 'csv';
} else {
newWhat = what.replace(/^url/, '');
}
const s = request('GET', data).getBody().toString('utf-8');
return new DataFrame(s, newWhat, colNames, dtypes);
} else if (isURL(data)) {
info('detected URL');
return new DataFrame(data, `url${what}`, colNames, dtypes);
} else if (what.startsWith('json')) {
info('data is JSON string, parsing');
if (what === 'json') {
info(`assuming input is JSON object`);
return new DataFrame(JSON.parse(data), 'obj', colNames, dtypes);
} else {
const hint = what.replace(/^json/, '');
info(`using further hint "${hint}"`);
return new DataFrame(JSON.parse(data), hint, colNames, dtypes);
}
} else if (what.startsWith('csv')) {
info('data is CSV string, parsing');
const rows = parseCSV(data, { skip_empty_lines: true, trim: true });
if (colNames === null) {
warn(`column names not provided, assuming first row is column names`);
const header = rows.splice(0, 1)[0];
return new DataFrame(rows, 'rows', header, dtypes);
} else {
debug(`using provided column names ${colNames.toString()}`);
return new DataFrame(rows, 'rows', colNames, dtypes);
}
} else if (what.startsWith('file')) {
info(`data is file "${data}"`);
if (what === 'file') {
const ext = (/\.([^.]+)$/i.exec(data) || [null, 'csv'])[1];
info(`using extension ".${ext}" as hint`);
return new DataFrame(readFileSync(data).toString('utf-8'), ext, colNames, dtypes);
} else {
const newWhat = what.replace(/^file/i, '');
info(`using provided hint for file content type "${newWhat}"`);
return new DataFrame(readFileSync(data).toString('utf-8'), newWhat, colNames, dtypes);
}
} else if (existsSync(data)) {
info(`detected existing file "${data}"`);
return new DataFrame(data, 'file', colNames, dtypes);
// dataset name with *.csv ending (walk recursively)
} else if (data.search(/\.(csv|json)$/i) >= 0) {
info(`data is dataset file name "${data}"`);
for (const path of walkFiles(...opts.DATASETS)) {
if (path.endsWith(data)) {
debug(`located dataset "${path}"`);
return new DataFrame(path, 'file', colNames, dtypes);
}
}
// dataset name WITHOUT *.csv ending
} else {
info(`data is dataset name "${data}" (no extension)`);
for (const path of walkFiles(...opts.DATASETS)) {
if (path.search(new RegExp(`${data}\\.(json|csv)`, 'i')) >= 0) {
debug(`located dataset "${path}"`);
return new DataFrame(path, 'file', colNames, dtypes);
}
}
}
const lookedIn = opts.DATASETS.concat([dirname(data)]).map((p) => resolve(p)).join(', ');
throw new Error(`failed to find file, looked for a dataset in ${lookedIn} (you might want to push your dir to opts.DATASETS OR set 'what', see API)`);
} else if (what.startsWith('gen')) {
info(`input is generator`);
const rows = [];
for (const r of data()) {
rows.push(r);
}
let newWhat = 'rows';
if (what !== 'gen') {
newWhat = what.replace(/^gen/, '');
} else {
info('assuming row generator');
}
return new DataFrame(rows, newWhat, colNames, dtypes);
} else if (isGenerator(data)) {
info(`input is row generator`);
return new DataFrame(data, 'gen', colNames, dtypes);
// javascript Object (PARSED)
} else if (what.startsWith('obj')) {
info('received Object');
// if { String: Number | String }
for (const key of Object.keys(data)) {
const val = data[key];
if (isNumber(val) || isString(val)) {
info('treating keys as column 1 and values as column 2');
return new DataFrame(
[Object.keys(data), Object.values(data)],
'cols',
colNames === null ? ['Key', 'Value'] : colNames,
dtypes,
);
}
}
// else
info('treating keys as column names and values as columns');
return new DataFrame(
Object.values(data),
'cols',
Object.keys(data),
dtypes,
);
} else if (isObject(data)) {
info('detected Object');
return new DataFrame(data, `obj${what}`, colNames, dtypes);
// map { col1 => col2, ... }
} else if (what.startsWith('map')) {
info(`data is Map (len is ${data.size})`);
// reverse logic to Object (above)
for (const v of data.values()) {
if (!isString(v) && !isNumber(v)) {
info('using keys as column names and values as columns');
return new DataFrame(
[...data.values()],
'cols',
[...data.keys()],
dtypes,
);
}
}
info('using keys as column 1 and values as column 2');
const keys = [...data.keys()];
const values = [...data.values()];
return new DataFrame(
[keys, values],
'cols',
colNames === null ? ['Key', 'Value'] : colNames,
dtypes,
);
} else if (isMap(data)) {
info('detected Map');
return new DataFrame(data, `map${what}`, colNames, dtypes);
// array of rows
} else if (what.startsWith('rows')) {
info(`data is array of ${data.length} rows, transposing to columns`);
return new DataFrame(transpose(data), 'cols', colNames, dtypes);
// array of cols
} else if (what.startsWith('cols')) {
debug(`input is array of ${data.length} columns`);
this.cols = data.map((c, cIdx) => {
const printName = `col #${cIdx}${colNames !== null && colNames[cIdx] !== undefined ? ` (${colNames[cIdx]})` : ''}`;
const isCol = Column.isCol(c);
if (isCol) {
debug(`${printName} is already a Column`);
}
const dtypeGiven = dtypes !== null && dtypes[cIdx] !== null && dtypes[cIdx] !== undefined;
debug(dtypeGiven ? `dtype "${dtypes[cIdx]}" given for ${printName}` : `need to guess dtype of ${printName}`);
const noNeedToConvert = isCol && (!dtypeGiven || c.dtype === dtypes[cIdx]);
if (noNeedToConvert) {
debug(`no need to convert ${printName}`);
return c;
}
debug(`converting ${printName}`);
// else
return Column.from(c, !dtypes || !dtypes[cIdx] ? null : dtypes[cIdx], false);
});
const { nCols } = this;
if (colNames === null) {
this.colNames = Column.from(Array(nCols).fill('').map((_, idx) => `col${idx}`));
} else {
this.colNames = Column.from(colNames.map((cName) => cName.toString()), 's');
for (let i = 0; i < nCols; i++) {
const colName = this.colNames[i];
const attributes = {
get() { return this[i]; },
set(newCol) {
this[i] = Column.from(newCol);
debug(`column ${colName} replaced with ${this[i].toString()}`);
},
};
Object.defineProperty(this.cols, colName, attributes);
debug(`registered col.${colName} to point to col[${i}]`);
}
debug(`used provided column names: [${this.colNames.join(', ')}]`);
}
} else if (what === '') {
return new DataFrame(data, 'cols', colNames, dtypes);
} else throw new Error('unrecognised input data');
const attrNames = new Set(this.colNames);
const { nCols } = this;
// index using cols integers AND column names
for (let cIdx = 0; cIdx < nCols; cIdx++) {
attrNames.add(cIdx);
}
/*
* easy access e.g. df.age, df.salary
* easy replacement (assignment) of cols e.g. df.age = df2.age;
* easy broadcasting e.g. df.label = 0;
*/
for (const name of attrNames) {
if (this[name] === undefined && isString(name)) {
Object.defineProperty(this, name, {
get() { return this.col(name); },
set(val) {
this.cols[this.colIdx(name)] = isNumber(val) || isString(val)
// broadcast
? Column.repeat(this.length, val)
// replace
: val;
},
});
}
}
const isUndef = (f) => this[f] === undefined;
// functs and aggs are forwarded to the underlying column
for (const section of Object.keys(opts.AGG)) {
for (const f of opts.AGG[section].filter(isUndef)) {
switch (section) {
case 'num':
this[f] = function (...args) { return this.numeric.agg(f, ...args); };
break;
case 'str':
this[f] = function (...args) { return this.nominal.agg(f, ...args); };
break;
case 'all':
this[f] = function (...args) { return this.agg(f, ...args); };
break;
default:
throw new Error(`unrecognised section "${section}" in opts.AGG`);
}
}
}
// each function is a function (Column => Column)
for (const section of Object.keys(opts.FUNCTS)) {
for (const f of opts.FUNCTS[section].filter(isUndef)) {
switch (section) {
case 'num':
this[f] = function (colId = null, ...args) {
const resultDF = this.clone();
const numDF = this.numeric.call(colId, f, ...args);
const { numColIdxs } = this;
let numCIdx = 0;
for (let cIdx = 0; cIdx < nCols; cIdx++) {
if (numColIdxs.has(cIdx)) {
resultDF.cols[cIdx] = numDF.cols[numCIdx];
numCIdx++;
}
}
return resultDF;
};
break;
case 'str':
this[f] = function (colId = null, ...args) {
const resultDF = this.clone();
const strDF = this.nominal.call(colId, f, ...args);
const { numColIdxs } = this;
let strCIdx = 0;
for (let cIdx = 0; cIdx < nCols; cIdx++) {
if (!numColIdxs.has(cIdx)) {
resultDF.cols[cIdx] = strDF.cols[strCIdx];
strCIdx++;
}
}
return resultDF;
};
break;
case 'all':
this[f] = function (colId = null, ...args) { return this.call(colId, f, ...args); };
break;
default:
throw new Error(`unrecognised section "${section}" in opts.AGG`);
}
}
}
// special cases, when called *without* any param, treat as agg
for (const f of [
'add', 'sub', 'mul', 'div', 'pow'
].filter(isUndef)) {
this[f] = function (...args) {
if (args.length === 0) {
debug(`no args to this.${f}() so treating as aggregate`);
return this.numeric.agg(f);
} else {
const fst = args[0];
return this.numeric.call(fst, f, ...args.slice(1));
}
};
}
}
/**
* Construct a DataFrame from columns.
*
* @param {...ArrayLike<*>} cols
* @returns {DataFrame}
*/
static of(...cols) { return new DataFrame(cols, 'cols'); }
* [Symbol.iterator]() {
const { rows } = this;
const n = this.length;
for (let rIdx = 0; rIdx < n; rIdx++) {
yield rows[rIdx];
}
}
get rows() {
return new Proxy(this.cols, {
/**
* @param {Column[]} cols
* @param {number} idx
* @returns {Array<*>}
*/
get(cols, idx) { return cols.map((col) => col[idx]); },
/**
*
* @param {Column[]} cols
* @param {Array<*>} row
* @returns {boolean}
*/
has(cols, row) {
const nCols = cols.length;
if (nCols === 0) {
return false;
}
const nRows = cols[0].length;
for (let rIdx = 0; rIdx < nRows; rIdx++) {
let eq = true;
for (let cIdx = 0; cIdx < nCols; cIdx++) {
if (row[cIdx] !== cols[cIdx][rIdx]) {
eq = false;
break;
}
}
if (eq) {
return true;
}
}
return false;
},
/**
* @param {Column[]} cols
* @param {number} rIdx
* @param {Array<*>} val
*/
set(cols, rIdx, val) {
for (let cIdx = 0; cIdx < cols.length; cIdx++) {
// eslint-disable-next-line no-param-reassign
cols[cIdx][rIdx] = val[cIdx];
}
}
});
}
/**
* @returns {Set<number>} set of column indexes
*/
get numColIdxs() {
const colIdxs = new Set();
const { dtypes, nCols } = this;
for (let cIdx = 0; cIdx < nCols; cIdx++) {
if (dtypes[cIdx].search(dtypeRegex) >= 0) {
colIdxs.add(cIdx);
}
}
return Object.freeze(colIdxs);
}
/**
* @returns {Set<number>} set of column indexes
*/
get strColIdxs() {
const numCols = this.numColIdxs;
return Object.freeze(new Set(this.colNames.filter((_, idx) => !numCols.has(idx))));
}
/**
* @param {string|number} colId
* @returns {number} column index
*/
colIdx(colId) {
const msg = (m) => `${this.constructor.name}.colIdx() ${m}`;
// resolve named column
if (Number.isInteger(colId)) {
// resolve negative idx
if (colId < 0) {
const newColIdx = this.nCols + colId;
log.debug(msg(`colId ${colId} negative, resolving to #${newColIdx}`));
return this.colIdx(newColIdx);
} else if (colId >= this.nCols) {
throw new Error(msg(`#${colId}, no such column, out of bounds`));
} else {
return colId;
}
} else if (isString(colId)) {
const idx = this.colNames.findIndex((colName) => colName === colId);
if (idx < 0) {
throw new Error(msg(`failed to find matching column for "${colId}"`));
}
log.debug(msg(`col "${colId}" is string, resolved to #${idx}`));
return idx;
} else throw new Error(msg(`bad input, expected number or string but got ${colId}`));
}
/**
* @returns {DataFrame} a data frame with numeric cols
*/
get numeric() {
const { numColIdxs } = this;
return this.select((cId) => numColIdxs.has(this.colIdx(cId)));
}
/**
* @returns {DataFrame} a data frame with numeric cols
*/
get nominal() {
const { numColIdxs } = this;
return this.select((cId) => !numColIdxs.has(this.colIdx(cId)));
}
/**
* @param {string|number} colId
* @returns {string[]|TypedArray} column
*/
col(colId) { return this.cols[this.colIdx(colId)]; }
/**
* @param {?number} [n]
* @returns {DataFrame} data frame
*/
head(n = null) {
if (n === null) {
return this.tail(opts.HEAD_LEN);
}
return this.slice(0, n);
}
/**
* @param {?number} [n]
* @returns {DataFrame} data frame
*/
tail(n = null) {
if (n === null) {
return this.tail(opts.HEAD_LEN);
}
return this.slice(this.length - n, this.length);
}
/**
* @returns {number} number of rows
*/
get length() {
if (this.cols[0] === undefined) {
return 0;
} else {
return this.cols[0].length;
}
}
/**
* @returns {number} number of columns
*/
get nCols() { return this.cols.length; }
/**
* @param {...(string|number)} colIds
* @returns {DataFrame} data frame
*/
dtype(...colIds) {
if (colIds.length === 0) {
return this.dtype(...this.colNames);
}
const colIdxs = colIds.map((id) => this.colIdx(id));
return this.select((cIdx) => colIdxs.indexOf(cIdx) >= 0).agg((col) => col.dtype).rename(1, 'dtype');
}
/**
* @returns {ColStr} data types for all columns
*/
get dtypes() { return Column.from(this.cols.map((c) => c.dtype), 's'); }
/**
* @param {...(number|string|RegExp|function((string|number)): boolean)} params
* @returns {DataFrame} data frame
*/
select(...params) {
if (params.length === 0) {
throw new Error('the DF is empty because no column IDs provided, try: df.select(0, -2, 3)');
} else if (params.length === 1 && isRegExp(params[0])) {
const regex = params[0];
return this.select((cName) => isString(cName) && cName.search(regex) >= 0);
} else if (params.length === 1 && isFunction(params[0])) {
const f = params[0];
return this.select(...(this.colNames.filter((name) => f(name) || f(this.colIdx(name)))));
} else {
const cols = [];
const colNames = [];
const dtypes = [];
for (const i of new Set(params.map((id) => this.colIdx(id)))) {
cols.push(this.cols[i]);
colNames.push(this.colNames[i]);
dtypes.push(this.dtypes[i]);
}
return new DataFrame(cols, 'cols', colNames, dtypes);
}
}
/**
* @param {...(number|string|RegExp|function((string|number)): boolean)} params
* @returns {DataFrame} data frame
*/
selectRows(...params) {
if (params.length === 0) {
throw new Error('the DF is empty because no row IDs provided, try: df.selectRows(0, -2, 3)');
} else if (params.length === 2 && isRegExp(params[0])) {
return this.selectRows((val) => val.search(params[0]) >= 0, params[1]);
} else if (params.length === 2 && isFunction(params[0])) {
const colId = params[1];
const f = params[0];
// focus on one column
const col = this.col(colId);
const tests = Array(col.length).fill(false).map((_, rIdx) => f(col[rIdx], rIdx));
return new DataFrame(
this.cols.map((c) => c.filter((_, rIdx) => tests[rIdx])),
'cols',
[...this.colNames],
[...this.dtypes],
);
} else if (params.length === 1 && isFunction(params[0])) {
throw new Error(`${this.constructor.name}.selectRows() not implemented yet`);
} else if (params.reduce((ok, focus) => ok && isNumber(focus) && Number.isInteger(focus))) {
throw new Error(`${this.constructor.name}.selectRows() not implemented yet`);
} else {
throw new Error(`${this.constructor.name}.selectRows() didn't understand args ${params.map((x) => x.toString()).join(', ')}`);
}
}
/**
* @param {...(string|number)} params pairs of colId, newName
* @returns {DataFrame} data frame with renamed col
*/
rename(...params) {
const msg = (m) => `${this.constructor.name}.rename() ${m}`;
if (params.length === 1 && Array.isArray(params[0])) {
const pairs = params[0].map((newName, cIdx) => [cIdx, newName]);
const args = pairs.reduce((pair1, pair2) => pair1.concat(pair2), []);
return this.rename(...args);
} else if (params.length === 1 && this.nCols === 1) {
log.info(msg('colId not specified for rename'));
return this.rename(0, params[0]);
} else if (params.length % 2 !== 0) {
throw new Error(msg('you need to provide pairs of colId, newName (e.g. df.rename(1, "Width", -2, "Length"))'));
}
const colNames = [...this.colNames];
for (let i = 1; i < params.length; i += 2) {
const colId = params[i - 1];
const newName = params[i];
const colIdx = this.colIdx(colId);
colNames[colIdx] = newName;
}
return new DataFrame([...this.cols], 'cols', colNames, [...this.dtypes]);
}
/**
* @param {?number|string} [colId]
* @param {string|function(Col): Col} f
* @param {...*} args
* @returns {DataFrame} data frame with f applied to colId
*/
call(colId = null, f, ...args) {
if (isString(f)) {
return this.call(colId, (col) => col[f](...args));
}
if (colId === null) {
log.info(`${this.constructor.name}.call() colId not specified, running for all cols`);
return [...this.colNames].reduce((df, cName) => df.call(cName, f, ...args), this);
}
const cols = [...this.cols];
const cIdx = this.colIdx(colId);
cols[cIdx] = f(cols[cIdx], ...args);
return new DataFrame(cols, 'cols', [...this.colNames], this.dtypes.map((t, idx) => idx === cIdx ? null : t));
}
/**
* @param {number} idx
* @returns {string}
* @private
*/
_colName(idx) {
return `col #${idx}${this.colNames[idx] === idx ? '' : ` (${this.colNames[idx]})`} dtype ${this.dtypes[idx]}`;
}
/**
* @param {function(ColNum): number} [f]
* @param {...*} args
* @returns {DataFrame} data frame
*/
agg(f = (xs) => xs.length, ...args) {
if (isString(f)) {
return this.agg((col) => col[f](...args)).rename(-1, f);
}
const colNames = [];
const aggResults = [];
const { nCols } = this;
for (let cIdx = 0; cIdx < nCols; cIdx++) {
const col = this.cols[cIdx];
const colName = this.colNames[cIdx];
colNames.push(colName);
aggResults.push(f(col, ...args));
}
return new DataFrame(
[colNames, aggResults.map((x) => x.toString())],
'cols',
['column', 'agg'],
['s', null],
);
}
/**
* @param {number|string} colId
* @param {function(ColNum): number} [f]
* @param {...*} args
* @returns {DataFrame} data frame
*/
groupBy(colId, f = (xs) => xs.length, ...args) {
if (isString(f)) {
return this.groupBy(colId, (xs) => xs[f](...args)).rename(-1, f);
}
const cIdx = this.colIdx(colId);
const index = new Map();
for (const r of this) {
const v = r[cIdx];
const maybe = index.get(v);
if (maybe === undefined) {
index.set(v, [r]);
} else {
maybe.push(r);
}
}
for (const k of index.keys()) {
index.set(k, f(index.get(k)));
}
return new DataFrame(index, 'map', [this.colNames[cIdx], 'result'], [this.dtypes[cIdx], null]);
}
/**
* @param {string|function(Column, Column, Number): Column} f
* @param {?DataFrame} [other]
* @returns {DataFrame} data frame
*/
connect(f, other = null) {
if (other === null) {
return this.connect(f, this);
}
if (isString(f)) {
return this.connect((xs, ys, idx) => xs[f](ys, idx), other);
}
const cols = Array(this.cols.length).fill(null);
const colNames = Array(this.cols.length).fill(null);
const { nCols } = this;
for (let cIdx = 0; cIdx < nCols; cIdx++) {
cols[cIdx] = f(this.cols[cIdx], other.cols[cIdx], cIdx);
if (!isNumber(this.colNames[cIdx])) {
colNames[cIdx] = this.colNames[cIdx];
} else if (!isNumber(other.colNames[cIdx])) {
colNames[cIdx] = other.colNames[cIdx];
} else {
colNames[cIdx] = null;
}
}
return new DataFrame(cols, 'cols', colNames);
}
/**
* @param {function(Col, Col): (number|string)} f
* @param {?boolean} [withNames]
* @param {?boolean} [isCommutative]
* @param {*} [identity]
* @returns {DataFrame} data frame
*/
matrix(f, withNames = true, isCommutative = false, identity = null, ...args) {
if (isString(f)) {
return this.matrix((xs, ys) => xs[f](ys, ...args), withNames, isCommutative, identity);
}
const colIdxs = [];
const rows = [];
const cache = {};
const { nCols } = this;
const msg = (m) => `${this.constructor.name}.matrix() ${m}`;
const debug = (m) => log.debug(msg(m));
for (let yIdx = 0; yIdx < nCols; yIdx++) {
// else
colIdxs.push(yIdx);
rows.push([]);
for (let xIdx = 0; xIdx < nCols; xIdx++) {
// some ops have a fixed return value when applied to self f(xs, xs) == id
if (identity !== null && xIdx === yIdx) {
debug(`[skipping identity yIdx == xIdx, f(${this._colName(xIdx)}, ${this._colName(yIdx)}) = ${identity}`);
rows[rows.length - 1].push(identity);
continue;
}
const col = this.cols[yIdx];
const other = this.cols[xIdx];
let result;
// sometimes order does not matter: f(xs, ys) === f(ys, xs)
if (isCommutative) {
result = cache[`${yIdx}:${xIdx}`];
// try swap
if (result === undefined) {
result = cache[`${xIdx}:${yIdx}`];
}
// if fail, compute
if (result === undefined) {
result = f(col, other, ...args);
cache[`${yIdx}:${xIdx}`] = result;
debug(`computed and cached f(${this._colName(yIdx)}, ${this._colName(xIdx)})`);
} else {
debug(`CACHE HIT for f(${this._colName(yIdx)}, ${this._colName(xIdx)})`);
}
rows[rows.length - 1].push(result);
} else {
rows[rows.length - 1].push(f(col, other, ...args));
}
}
}
// numeric col names in the order of appearing in the matrix
const colNames = this.colNames.filter((_, cIdx) => colIdxs.indexOf(cIdx) >= 0);
const df = new DataFrame(rows, 'rows', colNames);
return withNames ? df.prependCol(this.colNames.clone(), 'column') : df;
}
/**
* @param {string[]|number[]|TypedArray} col
* @param {?String} [name]
* @param {?DType|'s'} [dtype]
* @returns {DataFrame} data frame
*/
appendCol(col, name = null, dtype = null) {
const cols = [...this.cols];
const colNames = [...this.colNames];
const dtypes = [...this.dtypes];
cols.push(col);
colNames.push(name === null ? colNames.length : name);
dtypes.push(dtype === null ? null : dtype);
return new DataFrame(
cols,
'cols',
colNames,
dtypes,
);
}
/**
* @param {string[]|number[]|TypedArray} col
* @param {?String} [name]
* @param {?DType|'s'} [dtype]
* @returns {DataFrame} data frame
*/
prependCol(col, name = null, dtype = null) {
const cols = [...this.cols];
const colNames = [...this.colNames];
const dtypes = [...this.dtypes];
cols.unshift(col);
colNames.unshift(name === null ? colNames.length : name);
dtypes.unshift(dtype === null ? null : dtype);
return new DataFrame(
cols,
'cols',
colNames,
dtypes,
);
}
/**
* @param {DataFrame} other
* @param {'col'|'row'|'cols'|'rows'|0|1} [axis]
* @returns {DataFrame} data frame
*/
concat(other, axis = 0) {
if (isNumber(axis)) {
if (axis < 0) {
return this.concat(other, axis + 2);
} else if (axis === 0) {
return this.connect('concat', other);
} else if (axis === 1) {
// else if concat HORIZONTALLY
const isDigit = /^\d+$/; // check if has proper column names or just indexes
// if columns are indexes, shift them
let colNames;
if (other.colNames.filter((c) => c.toString().search(isDigit)).length === other.colNames.length) {
colNames = this.colNames.concat(other.colNames.map((cIdx) => this.colNames.length + cIdx));
} else {
colNames = this.colNames.concat(other.colNames);
}
let renamed;
/*
* deal with duplicate col names (add a num to the -- e.g.: Age, Salary, Age2 ...)
* make sure that name clash didn't arise as a result of previous renaming
*/
do {
renamed = false; // clear
for (let cIdx = 0; cIdx < colNames.length; cIdx++) {
const name = colNames[cIdx];
let count = 2;
for (let ptr = cIdx + 1; ptr < colNames.length; ptr++) {
const name2 = colNames[ptr];
if (name === name2) {
colNames[ptr] += count.toString();
renamed = true;
count++;
}
}
}
} while (renamed);
return new DataFrame(this.cols.concat(other.cols), 'cols', colNames);
}
} else if (isString(axis)) {
if (axis.search(/^col/i) >= 0) {
return this.concat(other, 1);
} else if (axis.search(/^row/i) >= 0) {
return this.concat(other, 0);
}
}
throw new Error(`${this.constructor.name}.concat() invalid axis argument ${axis}, try 0, 1, 'rows' or 'cols'`);
}
/**
* @param {...number} idxs PAIRS of indexes
* @returns {DataFrame} a data frame
*/
slice(...idxs) {
if (idxs.length === 0) {
throw new Error('you need to specify indexes (e.g. df.slice(0, 10), df.slice(-20, -10))');
} else if (idxs.length % 2 !== 0) {
idxs.push(this.length); // odd number of idxs
/*
* e.g. slice(0) -> slice(0, end)
* e.g. slice(0, 10, 20) -> slice(0, 10, 20, end)
*/
} else if (idxs.some((idx) => idx < 0)) {
// resolve negative indexes
return this.slice(...(idxs.map((idx) => (idx < 0 ? idx + this.length : idx))));
}
const { nCols } = this;
const cols = Array(nCols).fill(0);
// for every pair of indexes
for (let i = 1; i < idxs.length; i += 2) {
const lBound = idxs[i - 1];
const rBound = idxs[i];
for (let cIdx = 0; cIdx < nCols; cIdx++) {
const col = this.cols[cIdx];
cols[cIdx] = col.subarray(lBound, rBound);
}
}
return new DataFrame(cols, 'cols', [...this.colNames]);
}
/**
* E.g. sliceCols(0) -> sliceCols(0, end).
* E.g. sliceCols(0, 10, 20) -> sliceCols(0, 10, 20, end).
*
* @param {...(number|string)} slices
* @returns {DataFrame} data frame
*/
sliceCols(...slices) {
const msg = (m) => `${this.constructor.name}.sliceCols() ${m}`;
if (slices.length === 0) {
throw new Error(msg('no slice idxs specified (e.g. df.sliceCols(0, -1))'));
} else if (slices.length % 2 !== 0) {
// odd number of idxs
return this.sliceCols(...slices, this.nCols - 1);
}
// collect column idxs
const colIds = new Set();
const { nCols } = this;
for (let i = 1; i < slices.length; i += 2) {
const lBound = this.colIdx(slices[i - 1]);