-
-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathframe.ts
More file actions
3457 lines (3090 loc) · 119 KB
/
frame.ts
File metadata and controls
3457 lines (3090 loc) · 119 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
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
/**
* @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 dummyEncode from "../transformers/encoders/dummy.encoder";
import { variance, std, median, mode, mean } from 'mathjs';
import tensorflow from '../shared/tensorflowlib'
import { DATA_TYPES } from '../shared/defaults';
import { _genericMathOp } from "./math.ops";
import Groupby from '../aggregators/groupby';
import ErrorThrower from "../shared/errors"
import { _iloc, _loc } from "./indexing";
import Utils from "../shared/utils"
import NDframe from "./generic";
import { table } from "table";
import Series from './series';
import {
ArrayType1D,
ArrayType2D,
DataFrameInterface,
BaseDataOptionType,
IPlotlyLib,
} from "../shared/types";
import { PlotlyLib } from "../../danfojs-base/plotting";
const utils = new Utils();
/**
* Two-dimensional ndarray with axis labels.
* The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
* Operations between DataFrame (+, -, /, , *) align values based on their associated index values– they need not be the same length.
* @param data 2D Array, JSON, Tensor, Block of data.
* @param options.index Array of numeric or string names for subseting array. If not specified, indexes are auto generated.
* @param options.columns Array of column names. If not specified, column names are auto generated.
* @param options.dtypes Array of data types for each the column. If not specified, dtypes are/is inferred.
* @param options.config General configuration object for extending or setting NDframe behavior.
*/
export default class DataFrame extends NDframe implements DataFrameInterface {
[key: string]: any
constructor(data: any, options: BaseDataOptionType = {}) {
const { index, columns, dtypes, config } = options;
super({ data, index, columns, dtypes, config, isSeries: false });
this.$setInternalColumnDataProperty();
}
/**
* Maps all column names to their corresponding data, and return them as Series objects.
* This makes column subsetting works. E.g this can work ==> `df["col1"]`
* @param column Optional, a single column name to map
*/
private $setInternalColumnDataProperty(column?: string) {
const self = this;
if (column && typeof column === "string") {
Object.defineProperty(self, column, {
get() {
return self.$getColumnData(column)
},
set(arr: ArrayType1D | Series) {
self.$setColumnData(column, arr);
}
})
} else {
const columns = this.columns;
for (let i = 0; i < columns.length; i++) {
const column = columns[i];
Object.defineProperty(this, column, {
get() {
return self.$getColumnData(column)
},
set(arr: ArrayType1D | Series) {
self.$setColumnData(column, arr);
}
})
}
}
}
/**
* Returns the column data from the DataFrame by column name.
* @param column column name to get the column data
* @param returnSeries Whether to return the data in series format or not. Defaults to true
*/
private $getColumnData(column: string, returnSeries: boolean = true) {
const columnIndex = this.columns.indexOf(column)
if (columnIndex == -1) {
ErrorThrower.throwColumnNotFoundError(this)
}
const dtypes = [this.$dtypes[columnIndex]]
const index = [...this.$index]
const columns = [column]
const config = { ...this.$config }
if (this.$config.isLowMemoryMode) {
const data: ArrayType1D = []
for (let i = 0; i < this.values.length; i++) {
const row: any = this.values[i];
data.push(row[columnIndex])
}
if (returnSeries) {
return new Series(data, {
dtypes,
index,
columns,
config
})
} else {
return data
}
} else {
const data = this.$dataIncolumnFormat[columnIndex]
if (returnSeries) {
return new Series(data, {
dtypes,
index,
columns,
config
})
} else {
return data
}
}
}
/**
* Updates the internal column data via column name.
* @param column The name of the column to update.
* @param arr The new column data
*/
private $setColumnData(column: string, arr: ArrayType1D | Series): void {
const columnIndex = this.$columns.indexOf(column)
if (columnIndex == -1) {
throw new Error(`ParamError: column ${column} not found in ${this.$columns}. If you need to add a new column, use the df.addColumn method. `)
}
let colunmValuesToAdd: ArrayType1D
if (arr instanceof Series) {
colunmValuesToAdd = arr.values as ArrayType1D
} else if (Array.isArray(arr)) {
colunmValuesToAdd = arr;
} else {
throw new Error("ParamError: specified value not supported. It must either be an Array or a Series of the same length")
}
if (colunmValuesToAdd.length !== this.shape[0]) {
ErrorThrower.throwColumnLengthError(this, colunmValuesToAdd.length)
}
if (this.$config.isLowMemoryMode) {
//Update row ($data) array
for (let i = 0; i < this.$data.length; i++) {
(this.$data as any)[i][columnIndex] = colunmValuesToAdd[i]
}
//Update the dtypes
this.$dtypes[columnIndex] = utils.inferDtype(colunmValuesToAdd)[0]
} else {
//Update row ($data) array
for (let i = 0; i < this.values.length; i++) {
(this.$data as any)[i][columnIndex] = colunmValuesToAdd[i]
}
//Update column ($dataIncolumnFormat) array since it's available in object
(this.$dataIncolumnFormat as any)[columnIndex] = arr
//Update the dtypes
this.$dtypes[columnIndex] = utils.inferDtype(colunmValuesToAdd)[0]
}
}
/**
* Return data with missing values removed from a specified axis
* @param axis 0 or 1. If 0, column-wise, if 1, row-wise
*/
private $getDataByAxisWithMissingValuesRemoved(axis: number): Array<number[]> {
const oldValues = this.$getDataArraysByAxis(axis);
const cleanValues = [];
for (let i = 0; i < oldValues.length; i++) {
const values = oldValues[i] as number[]
cleanValues.push(utils.removeMissingValuesFromArray(values) as number[]);
}
return cleanValues;
}
/**
* Return data aligned to the specified axis. Transposes the array if needed.
* @param axis 0 or 1. If 0, column-wise, if 1, row-wise
*/
private $getDataArraysByAxis(axis: number): ArrayType2D {
if (axis === 1) {
return this.values as ArrayType2D
} else {
let dfValues;
if (this.config.isLowMemoryMode) {
dfValues = utils.transposeArray(this.values) as ArrayType2D
} else {
dfValues = this.$dataIncolumnFormat as ArrayType2D
}
return dfValues
}
}
/*
* checks if DataFrame is compactible for arithmetic operation
* compatible Dataframe must have only numerical dtypes
**/
private $frameIsNotCompactibleForArithmeticOperation() {
const dtypes = this.dtypes;
const str = (element: any) => element == "string";
return dtypes.some(str)
}
/**
* Return Tensors in the right axis for math operations.
* @param other DataFrame or Series or number or array
* @param axis 0 or 1. If 0, column-wise, if 1, row-wise
* */
private $getTensorsForArithmeticOperationByAxis(
other: DataFrame | Series | number | Array<number>,
axis: number
) {
if (typeof other === "number") {
return [this.tensor, tensorflow.scalar(other)];
} else if (other instanceof DataFrame) {
return [this.tensor, other.tensor];
} else if (other instanceof Series) {
if (axis === 0) {
return [this.tensor, tensorflow.tensor2d(other.values as Array<number>, [other.shape[0], 1])];
} else {
return [this.tensor, tensorflow.tensor2d(other.values as Array<number>, [other.shape[0], 1]).transpose()];
}
} else if (Array.isArray(other)) {
if (axis === 0) {
return [this.tensor, tensorflow.tensor2d(other, [other.length, 1])];
} else {
return [this.tensor, tensorflow.tensor2d(other, [other.length, 1]).transpose()];
}
} else {
throw new Error("ParamError: Invalid type for other parameter. other must be one of Series, DataFrame or number.")
}
}
/**
* Returns the dtype for a given column name
* @param column
*/
private $getColumnDtype(column: string): string {
const columnIndex = this.columns.indexOf(column)
if (columnIndex === -1) {
throw Error(`ColumnNameError: Column "${column}" does not exist`)
}
return this.dtypes[columnIndex]
}
private $logicalOps(tensors: typeof tensorflow.Tensor[], operation: string) {
let newValues: number[] = []
switch (operation) {
case 'gt':
newValues = tensors[0].greater(tensors[1]).arraySync() as number[]
break;
case 'lt':
newValues = tensors[0].less(tensors[1]).arraySync() as number[]
break;
case 'ge':
newValues = tensors[0].greaterEqual(tensors[1]).arraySync() as number[]
break;
case 'le':
newValues = tensors[0].lessEqual(tensors[1]).arraySync() as number[]
break;
case 'eq':
newValues = tensors[0].equal(tensors[1]).arraySync() as number[]
break;
case 'ne':
newValues = tensors[0].notEqual(tensors[1]).arraySync() as number[]
break;
}
const newData = utils.mapIntegersToBooleans(newValues, 2)
return new DataFrame(
newData,
{
index: [...this.index],
columns: [...this.columns],
dtypes: [...this.dtypes],
config: { ...this.config }
})
}
private $MathOps(tensors: typeof tensorflow.Tensor[], operation: string, inplace: boolean) {
let tensorResult
switch (operation) {
case 'add':
tensorResult = tensors[0].add(tensors[1])
break;
case 'sub':
tensorResult = tensors[0].sub(tensors[1])
break;
case 'pow':
tensorResult = tensors[0].pow(tensors[1])
break;
case 'div':
tensorResult = tensors[0].div(tensors[1])
break;
case 'divNoNan':
tensorResult = tensors[0].divNoNan(tensors[1])
break;
case 'mul':
tensorResult = tensors[0].mul(tensors[1])
break;
case 'mod':
tensorResult = tensors[0].mod(tensors[1])
break;
}
if (inplace) {
const newData = tensorResult?.arraySync() as ArrayType2D
this.$setValues(newData)
} else {
return new DataFrame(
tensorResult,
{
index: [...this.index],
columns: [...this.columns],
dtypes: [...this.dtypes],
config: { ...this.config }
})
}
}
/**
* Purely integer-location based indexing for selection by position.
* ``.iloc`` is primarily integer position based (from ``0`` to
* ``length-1`` of the axis), but may also be used with a boolean array.
*
* @param rows Array of row indexes
* @param columns Array of column indexes
*
* Allowed inputs are in rows and columns params are:
*
* - An array of single integer, e.g. ``[5]``.
* - A list or array of integers, e.g. ``[4, 3, 0]``.
* - A slice array string with ints, e.g. ``["1:7"]``.
* - A boolean array.
* - A ``callable`` function with one argument (the calling Series or
* DataFrame) and that returns valid output for indexing (one of the above).
* This is useful in method chains, when you don't have a reference to the
* calling object, but would like to base your selection on some value.
*
* ``.iloc`` will raise ``IndexError`` if a requested indexer is
* out-of-bounds.
*
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.iloc({ rows: [1], columns: ["A"] })
* ```
*/
iloc({ rows, columns }: {
rows?: Array<string | number | boolean> | Series,
columns?: Array<string | number>
}): DataFrame {
return _iloc({ ndFrame: this, rows, columns }) as DataFrame;
}
/**
* Access a group of rows and columns by label(s) or a boolean array.
* ``loc`` is primarily label based, but may also be used with a boolean array.
*
* @param rows Array of row indexes
* @param columns Array of column indexes
*
* Allowed inputs are:
*
* - A single label, e.g. ``["5"]`` or ``['a']``, (note that ``5`` is interpreted as a
* *label* of the index, and **never** as an integer position along the index).
*
* - A list or array of labels, e.g. ``['a', 'b', 'c']``.
*
* - A slice object with labels, e.g. ``["a:f"]``. Note that start and the stop are included
*
* - A boolean array of the same length as the axis being sliced,
* e.g. ``[True, False, True]``.
*
* - A ``callable`` function with one argument (the calling Series or
* DataFrame) and that returns valid output for indexing (one of the above)
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.loc({ rows: [1], columns: ["A"] })
* ```
*/
loc({ rows, columns }: {
rows?: Array<string | number | boolean> | Series,
columns?: Array<string>
}): DataFrame {
return _loc({ ndFrame: this, rows, columns }) as DataFrame
}
/**
* Prints DataFrame to console as a formatted grid of row and columns.
*/
toString(): string {
const maxRow = this.config.getMaxRow;
const maxColToDisplayInConsole = this.config.getTableMaxColInConsole;
// let data;
const dataArr: ArrayType2D = [];
const colLen = this.columns.length;
let header = [];
if (colLen > maxColToDisplayInConsole) {
//truncate displayed columns to fit in the console
let firstFourcolNames = this.columns.slice(0, 4);
let lastThreecolNames = this.columns.slice(colLen - 3);
//join columns with truncate ellipse in the middle
header = ["", ...firstFourcolNames, "...", ...lastThreecolNames];
let subIdx: Array<number | string>
let firstHalfValues: ArrayType2D
let lastHalfValueS: ArrayType2D
if (this.values.length > maxRow) {
//slice Object to show [max_rows]
let dfSubset1 = this.iloc({
rows: [`0:${maxRow}`],
columns: ["0:4"]
});
let dfSubset2 = this.iloc({
rows: [`0:${maxRow}`],
columns: [`${colLen - 3}:`]
});
subIdx = this.index.slice(0, maxRow);
firstHalfValues = dfSubset1.values as ArrayType2D
lastHalfValueS = dfSubset2.values as ArrayType2D
} else {
let dfSubset1 = this.iloc({ columns: ["0:4"] });
let dfSubset2 = this.iloc({ columns: [`${colLen - 3}:`] });
subIdx = this.index.slice(0, maxRow);
firstHalfValues = dfSubset1.values as ArrayType2D
lastHalfValueS = dfSubset2.values as ArrayType2D
}
// merge subset
for (let i = 0; i < subIdx.length; i++) {
const idx = subIdx[i];
const row = [idx, ...firstHalfValues[i], "...", ...lastHalfValueS[i]]
dataArr.push(row);
}
} else {
//display all columns
header = ["", ...this.columns]
let subIdx
let values: ArrayType2D
if (this.values.length > maxRow) {
//slice Object to show a max of [max_rows]
let data = this.iloc({ rows: [`0:${maxRow}`] });
subIdx = data.index;
values = data.values as ArrayType2D
} else {
values = this.values as ArrayType2D
subIdx = this.index;
}
// merge subset
for (let i = 0; i < subIdx.length; i++) {
const idx = subIdx[i];
const row = [idx, ...values[i]];
dataArr.push(row);
}
}
const columnsConfig: any = {};
columnsConfig[0] = { width: 10 }; //set column width for index column
for (let index = 1; index < header.length; index++) {
columnsConfig[index] = { width: 17, truncate: 16 };
}
const tableData: any = [header, ...dataArr]; //Adds the column names to values before printing
return table(tableData, { columns: columnsConfig, ...this.config.getTableDisplayConfig });
}
/**
* Returns the first n values in a DataFrame
* @param rows The number of rows to return
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B']})
* const df2 = df.head(1)
* ```
*/
head(rows: number = 5): DataFrame {
if (rows <= 0) {
throw new Error("ParamError: Number of rows cannot be less than 1")
}
if (this.shape[0] <= rows) {
return this.copy()
}
if (this.shape[0] - rows < 0) {
throw new Error("ParamError: Number of rows cannot be greater than available rows in data")
}
return this.iloc({ rows: [`0:${rows}`] })
}
/**
* Returns the last n values in a DataFrame
* @param rows The number of rows to return
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B']})
* const df2 = df.tail(1)
* ```
*/
tail(rows: number = 5): any {
if (rows <= 0) {
throw new Error("ParamError: Number of rows cannot be less than 1")
}
if (this.shape[0] <= rows) {
return this.copy()
}
if (this.shape[0] - rows < 0) {
throw new Error("ParamError: Number of rows cannot be greater than available rows in data")
}
rows = this.shape[0] - rows
return this.iloc({ rows: [`${rows}:`] })
}
/**
* Gets n number of random rows in a dataframe. Sample is reproducible if seed is provided.
* @param num The number of rows to return. Default to 5.
* @param options.seed An integer specifying the random seed that will be used to create the distribution.
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = await df.sample(1)
* ```
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = await df.sample(1, { seed: 1 })
* ```
*/
async sample(num = 5, options?: { seed?: number }): Promise<DataFrame> {
const { seed } = { seed: 1, ...options }
if (num > this.shape[0]) {
throw new Error("ParamError: Sample size cannot be bigger than number of rows");
}
if (num <= 0) {
throw new Error("ParamError: Sample size cannot be less than 1");
}
const shuffledIndex = await tensorflow.data.array(this.index).shuffle(num, `${seed}`).take(num).toArray();
const df = this.iloc({ rows: shuffledIndex });
return df;
}
/**
* Return Addition of DataFrame and other, element-wise (binary operator add).
* @param other DataFrame, Series, Array or Scalar number to add
* @param options.axis 0 or 1. If 0, add column-wise, if 1, add row-wise
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.add(1)
* df2.print()
* ```
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* df.add([1, 2], { axis: 0, inplace: true})
* df.print()
* ```
*/
add(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame
add(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame | void {
const { inplace, axis } = { inplace: false, axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: add operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const tensors = this.$getTensorsForArithmeticOperationByAxis(other, axis);
return this.$MathOps(tensors, "add", inplace)
}
/**
* Return substraction between DataFrame and other.
* @param other DataFrame, Series, Array or Scalar number to substract from DataFrame
* @param options.axis 0 or 1. If 0, compute the subtraction column-wise, if 1, row-wise
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.sub(1)
* df2.print()
* ```
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* df.sub([1, 2], { axis: 0, inplace: true})
* df.print()
* ```
*/
sub(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame
sub(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame | void {
const { inplace, axis } = { inplace: false, axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: sub operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const tensors = this.$getTensorsForArithmeticOperationByAxis(other, axis);
return this.$MathOps(tensors, "sub", inplace)
}
/**
* Return multiplciation between DataFrame and other.
* @param other DataFrame, Series, Array or Scalar number to multiply with.
* @param options.axis 0 or 1. If 0, compute the multiplication column-wise, if 1, row-wise
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.mul(2)
* df2.print()
* ```
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* df.mul([1, 2], { axis: 0, inplace: true})
* df.print()
* ```
*/
mul(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame
mul(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame | void {
const { inplace, axis } = { inplace: false, axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: mul operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const tensors = this.$getTensorsForArithmeticOperationByAxis(other, axis);
return this.$MathOps(tensors, "mul", inplace)
}
/**
* Return division of DataFrame with other.
* @param other DataFrame, Series, Array or Scalar number to divide with.
* @param options.axis 0 or 1. If 0, compute the division column-wise, if 1, row-wise
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.div(2)
* df2.print()
* ```
*/
div(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame
div(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame | void {
const { inplace, axis } = { inplace: false, axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: div operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const tensors = this.$getTensorsForArithmeticOperationByAxis(other, axis);
return this.$MathOps(tensors, "div", inplace)
}
/**
* Return division of DataFrame with other, returns 0 if denominator is 0.
* @param other DataFrame, Series, Array or Scalar number to divide with.
* @param options.axis 0 or 1. If 0, compute the division column-wise, if 1, row-wise
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.divNoNan(2)
* df2.print()
* ```
*/
divNoNan(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame
divNoNan(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame | void {
const { inplace, axis } = { inplace: false, axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: div operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const tensors = this.$getTensorsForArithmeticOperationByAxis(other, axis);
return this.$MathOps(tensors, "divNoNan", inplace)
}
/**
* Return DataFrame raised to the power of other.
* @param other DataFrame, Series, Array or Scalar number to to raise to.
* @param options.axis 0 or 1. If 0, compute the power column-wise, if 1, row-wise
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.pow(2)
* df2.print()
* ```
*/
pow(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame
pow(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame | void {
const { inplace, axis } = { inplace: false, axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: pow operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const tensors = this.$getTensorsForArithmeticOperationByAxis(other, axis);
return this.$MathOps(tensors, "pow", inplace)
}
/**
* Return modulus between DataFrame and other.
* @param other DataFrame, Series, Array or Scalar number to modulus with.
* @param options.axis 0 or 1. If 0, compute the mod column-wise, if 1, row-wise
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* const df2 = df.mod(2)
* df2.print()
* ```
*/
mod(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame
mod(other: DataFrame | Series | number[] | number, options?: { axis?: 0 | 1, inplace?: boolean }): DataFrame | void {
const { inplace, axis } = { inplace: false, axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: mod operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const tensors = this.$getTensorsForArithmeticOperationByAxis(other, axis);
return this.$MathOps(tensors, "mod", inplace)
}
/**
* Return mean of DataFrame across specified axis.
* @param options.axis 0 or 1. If 0, compute the mean column-wise, if 1, row-wise. Defaults to 1
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* df.mean().print()
* ```
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B'] })
* df.mean({ axis: 0 }).print()
* ```
*/
mean(options?: { axis?: 0 | 1 }): Series {
const { axis } = { axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: mean operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const newData = this.$getDataByAxisWithMissingValuesRemoved(axis)
const resultArr = newData.map(arr => arr.reduce((a, b) => a + b, 0) / arr.length)
if (axis === 0) {
return new Series(resultArr, { index: this.columns });
} else {
return new Series(resultArr, { index: this.index });
}
}
/**
* Return median of DataFrame across specified axis.
* @param options.axis 0 or 1. If 0, compute the median column-wise, if 1, row-wise. Defaults to 1
* @example
* ```
* const df = new DataFrame([[1, 2, 4], [3, 4, 5], [6, 7, 8]], { columns: ['A', 'B', 'C'] });
* df.median().print()
* ```
*/
median(options?: { axis?: 0 | 1 }): Series {
const { axis } = { axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: median operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const newData = this.$getDataByAxisWithMissingValuesRemoved(axis)
const resultArr = newData.map(arr => median(arr))
if (axis === 0) {
return new Series(resultArr, { index: this.columns });
} else {
return new Series(resultArr, { index: this.index });
}
}
/**
* Return mode of DataFrame across specified axis.
* @param options.axis 0 or 1. If 0, compute the mode column-wise, if 1, row-wise. Defaults to 1
* @param options.keep If there are more than one modes, returns the mode at position [keep]. Defaults to 0
* @example
* ```
* const df = new DataFrame([[1, 2, 4], [3, 4, 5], [6, 7, 8]], { columns: ['A', 'B', 'C'] });
* df.mode().print()
* ```
* @example
* ```
* const df = new DataFrame([[1, 2, 4], [3, 4, 5], [6, 7, 8]], { columns: ['A', 'B', 'C'] });
* df.mode({ keep: 1 }).print()
* ```
*/
mode(options?: { axis?: 0 | 1, keep?: number }): Series {
const { axis, keep } = { axis: 1, keep: 0, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: mode operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const newData = this.$getDataByAxisWithMissingValuesRemoved(axis)
const resultArr = newData.map(arr => {
const tempMode = mode(arr)
if (tempMode.length === 1) {
return tempMode[0]
} else {
return tempMode[keep]
}
})
if (axis === 0) {
return new Series(resultArr, { index: this.columns });
} else {
return new Series(resultArr, { index: this.index });
}
}
/**
* Return minimum of values in a DataFrame across specified axis.
* @param options.axis 0 or 1. If 0, compute the minimum value column-wise, if 1, row-wise. Defaults to 1
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B']})
* df.min().print()
* ```
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B']})
* df.min({ axis: 0 }).print()
* ```
*/
min(options?: { axis?: 0 | 1 }): Series {
const { axis } = { axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: min operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const newData = this.$getDataByAxisWithMissingValuesRemoved(axis)
const resultArr = newData.map(arr => {
let smallestValue = arr[0]
for (let i = 0; i < arr.length; i++) {
smallestValue = smallestValue < arr[i] ? smallestValue : arr[i]
}
return smallestValue
})
if (axis === 0) {
return new Series(resultArr, { index: this.columns });
} else {
return new Series(resultArr, { index: this.index });
}
}
/**
* Return maximum of values in a DataFrame across specified axis.
* @param options.axis 0 or 1. If 0, compute the maximum column-wise, if 1, row-wise. Defaults to 1
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B']})
* df.max().print()
* ```
* @example
* ```
* const df = new DataFrame([[1, 2], [3, 4]], { columns: ['A', 'B']})
* df.max({ axis: 0 }).print()
* ```
*/
max(options?: { axis?: 0 | 1 }): Series {
const { axis } = { axis: 1, ...options }
if (this.$frameIsNotCompactibleForArithmeticOperation()) {
throw Error("TypeError: max operation is not supported for string dtypes");
}
if ([0, 1].indexOf(axis) === -1) {
throw Error("ParamError: Axis must be 0 or 1");
}
const newData = this.$getDataByAxisWithMissingValuesRemoved(axis)
const resultArr = newData.map(arr => {
let biggestValue = arr[0]
for (let i = 0; i < arr.length; i++) {
biggestValue = biggestValue > arr[i] ? biggestValue : arr[i]
}
return biggestValue
})
if (axis === 0) {
return new Series(resultArr, { index: this.columns });
} else {