-
-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathseries.ts
More file actions
2199 lines (1995 loc) · 71 KB
/
series.ts
File metadata and controls
2199 lines (1995 loc) · 71 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 } from 'mathjs';
import tensorflow from '../shared/tensorflowlib'
import { DATA_TYPES } from '../shared/defaults'
import { _genericMathOp } from "./math.ops";
import ErrorThrower from "../shared/errors"
import { _iloc, _loc } from "./indexing";
import Utils from "../shared/utils"
import NDframe from "./generic";
import { table } from "table";
import Str from './strings';
import Dt from './datetime';
import DataFrame from "./frame";
import {
ArrayType1D,
BaseDataOptionType,
SeriesInterface,
mapParam,
IPlotlyLib
} from "../shared/types";
import { PlotlyLib } from "../../danfojs-base/plotting";
const utils = new Utils();
/**
* One-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 Series (+, -, /, , *) align values based on their associated index values – they need not be the same length.
* @param data 1D Array, JSON, Tensor, Block of data.
* @param options.index Array of numeric or string index for subseting array. If not specified, indices are auto generated.
* @param options.columns Column name. This is like the name of the Series. If not specified, column name is set to 0.
* @param options.dtypes Data types of the Series data. If not specified, dtypes is inferred.
* @param options.config General configuration object for extending or setting Series behavior.
*/
export default class Series extends NDframe implements SeriesInterface {
constructor(data: any = [], options: BaseDataOptionType = {}) {
const { index, columns, dtypes, config } = options;
if (Array.isArray(data[0]) || utils.isObject(data[0])) {
data = utils.convert2DArrayToSeriesArray(data);
super({
data,
index,
columns,
dtypes,
config,
isSeries: true
});
} else {
super({
data,
index,
columns,
dtypes,
config,
isSeries: true
});
}
}
/**
* 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
*
* 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 sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.iloc([0, 2, 4]);
* sf2.print();
* ```
*/
iloc(rows: Array<string | number | boolean>): Series {
return _iloc({ ndFrame: this, rows }) as Series
}
/**
* Access a group of rows 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
*
* 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 sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.loc(['a', 'c', 'e']);
* sf2.print();
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.loc(sf.gt(2));
* sf2.print();
* ```
*/
loc(rows: Array<string | number | boolean>): Series {
return _loc({ ndFrame: this, rows }) as Series
}
/**
* Returns the first n values in a Series
* @param rows The number of rows to return
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.head(3);
* sf2.print();
* ```
*/
head(rows: number = 5): Series {
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([`0:${rows}`])
}
/**
* Returns the last n values in a Series
* @param rows The number of rows to return
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.tail(3);
* sf2.print();
* ```
*/
tail(rows: number = 5): Series {
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")
}
const startIdx = this.shape[0] - rows
return this.iloc([`${startIdx}:`])
}
/**
* Returns specified number of random rows in a Series
* @param num The number of rows to return
* @param options.seed An integer specifying the random seed that will be used to create the distribution.
* @example
* ```
* const df = new Series([1, 2, 3, 4])
* const df2 = await df.sample(2)
* df2.print()
* ```
* @example
* ```
* const df = new Series([1, 2, 3, 4])
* const df2 = await df.sample(1, { seed: 1 })
* df2.print()
* ```
*/
async sample(num = 5, options?: { seed?: number }): Promise<Series> {
const { seed } = { seed: 1, ...options }
if (num > this.shape[0]) {
throw new Error("Sample size n cannot be bigger than size of dataset");
}
if (num < -1 || num == 0) {
throw new Error("Sample size cannot be less than -1 or be equal to 0");
}
num = num === -1 ? this.shape[0] : num;
const shuffledIndex = await tensorflow.data.array(this.index).shuffle(num, `${seed}`).take(num).toArray();
const sf = this.iloc(shuffledIndex);
return sf;
}
/**
* Return Addition of series and other, element-wise (binary operator add).
* Equivalent to series + other
* @param other Series, Array of same length or scalar number to add
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.add(2);
* console.log(sf2.values);
* //output [3, 4, 5, 6, 7, 8]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.add([2, 3, 4, 5, 6, 7]);
* console.log(sf2.values);
* //output [3, 5, 7, 9, 11, 13]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* sf.add(2, { inplace: true });
* console.log(sf.values);
* //output [3, 4, 5, 6, 7, 8]
* ```
*/
add(other: Series | Array<number> | number, options?: { inplace?: boolean }): Series
add(other: Series | Array<number> | number, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("add")
const newData = _genericMathOp({ ndFrame: this, other, operation: "add" })
if (inplace) {
this.$setValues(newData as ArrayType1D)
} else {
return utils.createNdframeFromNewDataWithOldProps({ ndFrame: this, newData, isSeries: true }) as Series
}
}
/**
* Returns the subtraction between a series and other, element-wise (binary operator subtraction).
* Equivalent to series - other
* @param other Number to subtract
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.sub(2);
* console.log(sf2.values);
* //output [-1, 0, 1, 2, 3, 4]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.sub([2, 3, 4, 5, 6, 7]);
* console.log(sf2.values);
* //output [-1, -1, -1, -1, -1, -1]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* sf.sub(2, { inplace: true });
* console.log(sf.values);
* //output [-1, 0, 1, 2, 3, 4]
* ```
*/
sub(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series
sub(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("sub")
const newData = _genericMathOp({ ndFrame: this, other, operation: "sub" })
if (inplace) {
this.$setValues(newData as ArrayType1D)
} else {
return utils.createNdframeFromNewDataWithOldProps({ ndFrame: this, newData, isSeries: true }) as Series
}
}
/**
* Return Multiplication of series and other, element-wise (binary operator mul).
* Equivalent to series * other
* @param other Number to multiply with.
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.mul(2);
* console.log(sf2.values);
* //output [2, 4, 6, 8, 10, 12]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.mul([2, 3, 4, 5, 6, 7]);
* console.log(sf2.values);
* //output [2, 6, 12, 20, 30, 42]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* sf.mul(2, { inplace: true });
* console.log(sf.values);
* //output [2, 4, 6, 8, 10, 12]
* ```
*/
mul(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series
mul(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("mul")
const newData = _genericMathOp({ ndFrame: this, other, operation: "mul" })
if (inplace) {
this.$setValues(newData as ArrayType1D)
} else {
return utils.createNdframeFromNewDataWithOldProps({ ndFrame: this, newData, isSeries: true }) as Series
}
}
/**
* Return division of series and other, element-wise (binary operator div).
* Equivalent to series / other
* @param other Series or number to divide with.
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.div(2);
* console.log(sf2.values);
* //output [0.5, 1, 1.5, 2, 2.5, 3]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.div([2, 3, 4, 5, 6, 7]);
* console.log(sf2.values);
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* sf.div(2, { inplace: true });
* console.log(sf.values);
* //output [0.5, 1, 1.5, 2, 2.5, 3]
* ```
*/
div(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series
div(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("div")
const newData = _genericMathOp({ ndFrame: this, other, operation: "div" })
if (inplace) {
this.$setValues(newData as ArrayType1D)
} else {
return utils.createNdframeFromNewDataWithOldProps({ ndFrame: this, newData, isSeries: true }) as Series
}
}
/**
* Return Exponential power of series and other, element-wise (binary operator pow).
* Equivalent to series ** other
* @param other Number to raise to power.
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.pow(2);
* console.log(sf2.values);
* //output [1, 4, 9, 16, 25, 36]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.pow(new Series([2, 3, 4, 5, 6, 7]));
* console.log(sf2.values);
* //output [ 1, 8, 81, 1024, 15625, 279936 ]
* ```
*
*/
pow(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series
pow(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("pow")
const newData = _genericMathOp({ ndFrame: this, other, operation: "pow" })
if (inplace) {
this.$setValues(newData as ArrayType1D)
} else {
return utils.createNdframeFromNewDataWithOldProps({ ndFrame: this, newData, isSeries: true }) as Series
}
}
/**
* Return Modulo of series and other, element-wise (binary operator mod).
* Equivalent to series % other
* @param other Number to modulo with
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.mod(2);
* console.log(sf2.values);
* //output [1, 0, 1, 0, 1, 0]
* ```
*/
mod(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series
mod(other: Series | number | Array<number>, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("mod")
const newData = _genericMathOp({ ndFrame: this, other, operation: "mod" })
if (inplace) {
this.$setValues(newData as ArrayType1D)
} else {
return utils.createNdframeFromNewDataWithOldProps({ ndFrame: this, newData, isSeries: true }) as Series
}
}
/**
* Checks if the array value passed has a compatible dtype, removes NaN values, and if
* boolean values are present, converts them to integer values.
*/
private $checkAndCleanValues(values: ArrayType1D, operation: string): number[] {
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError(operation)
values = utils.removeMissingValuesFromArray(values);
if (this.dtypes[0] == "boolean") {
values = (utils.mapBooleansToIntegers(values as boolean[], 1) as ArrayType1D);
}
return values as number[]
}
/**
* Returns the mean of elements in Series.
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.mean());
* //output 3.5
* ```
*/
mean(): number {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "mean")
return (values.reduce((a, b) => a + b) / values.length) as number
}
/**
* Returns the median of elements in Series
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.median());
* //output 3.5
* ```
*/
median(): number {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "median")
return median(values);
}
/**
* Returns the modal value of elements in Series
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 4, 5, 6]);
* console.log(sf.mode());
* //output [ 4 ]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 4, 5, 5, 6]);
* console.log(sf.mode());
* //output [ 4, 5 ]
* ```
*
*/
mode() {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "mode")
return mode(values);
}
/**
* Returns the minimum value in a Series
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.min());
* //output 1
* ```
*
*/
min(): number {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "min")
let smallestValue = values[0]
for (let i = 0; i < values.length; i++) {
smallestValue = smallestValue < values[i] ? smallestValue : values[i]
}
return smallestValue
}
/**
* Returns the maximum value in a Series
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.max());
* //output 6
* ```
*/
max(): number {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "max")
let biggestValue = values[0]
for (let i = 0; i < values.length; i++) {
biggestValue = biggestValue > values[i] ? biggestValue : values[i]
}
return biggestValue
}
/**
* Return the sum of the values in a series.
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.sum());
* //output 21
* ```
*/
sum(): number {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "sum")
return values.reduce((sum, value) => sum + value, 0)
}
/**
* Return number of non-null elements in a Series
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.count());
* //output 6
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6, NaN]);
* console.log(sf.count());
* //output 6
* ```
*/
count(): number {
const values = utils.removeMissingValuesFromArray(this.values as ArrayType1D)
return values.length
}
/**
* Return maximum of series and other.
* @param other Series, number or Array of numbers to check against
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = sf.maximum(3);
* console.log(sf2.values);
* //output [ 3, 3, 3, 4, 5, 6 ]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = new Series([4, 1, 3, 40, 5, 3]);
* const sf3 = sf.maximum(sf2);
* console.log(sf3.values);
* //output [ 4, 2, 3, 40, 5, 6 ]
* ```
*/
maximum(other: Series | number | Array<number>): Series {
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("maximum")
const newData = _genericMathOp({ ndFrame: this, other, operation: "maximum" })
return new Series(newData, {
columns: this.columns,
index: this.index
});
}
/**
* Return minimum of series and other.
* @param other Series, number of Array of numbers to check against
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = sf.minimum(3);
* console.log(sf2.values);
* //output [ 1, 2, 3, 3, 3, 3 ]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = new Series([4, 1, 3, 40, 5, 3]);
* const sf3 = sf.minimum(sf2);
* console.log(sf3.values);
* //output [ 1, 1, 3, 4, 5, 3 ]
* ```
*
*/
minimum(other: Series | number | Array<number>): Series {
if (this.dtypes[0] == "string") ErrorThrower.throwStringDtypeOperationError("maximum")
const newData = _genericMathOp({ ndFrame: this, other, operation: "minimum" })
return new Series(newData, {
columns: this.columns,
index: this.index
});
}
/**
* Round each value in a Series to the specified number of decimals.
* @param dp Number of Decimal places to round to
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
*
* @example
* ```
* const sf = new Series([1.23, 2.4, 3.123, 4.1234, 5.12345]);
* const sf2 = sf.round(2);
* console.log(sf2.values);
* //output [ 1.23, 2.4, 3.12, 4.12, 5.12 ]
* ```
*
* @example
* ```
* const sf = new Series([1.23, 2.4, 3.123, 4.1234, 5.12345]);
* sf.round(2, { inplace: true });
* console.log(sf.values);
* //output [ 1.23, 2.4, 3.12, 4.12, 5.12 ]
* ```
*/
round(dp?: number, options?: { inplace?: boolean }): Series
round(dp = 1, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (dp === undefined) dp = 1;
const newValues = utils.round(this.values as number[], dp, true);
if (inplace) {
this.$setValues(newValues)
} else {
return utils.createNdframeFromNewDataWithOldProps({
ndFrame: this,
newData: newValues,
isSeries: true
}) as Series
}
}
/**
* Return sample standard deviation of elements in Series
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.std());
* //output 1.8708286933869707
* ```
*/
std(): number {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "max")
return std(values);
}
/**
* Return unbiased variance of elements in a Series.
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* console.log(sf.var());
* //output 3.5
* ```
*/
var(): number {
const values = this.$checkAndCleanValues(this.values as ArrayType1D, "max")
return variance(values);
}
/**
* Return a boolean same-sized object indicating where elements are NaN.
* NaN and undefined values gets mapped to true, and everything else gets mapped to false.
* @example
* ```
* const sf = new Series([1, 2, 3, 4, NaN, 6]);
* console.log(sf.isNaN());
* //output [ false, false, false, false, true, false ]
* ```
*
*/
isNa(): Series {
const newData = this.values.map((value) => {
if (utils.isEmpty(value)) {
return true;
} else {
return false;
}
})
const sf = new Series(newData,
{
index: this.index,
dtypes: ["boolean"],
config: this.config
});
return sf;
}
/**
* Replace all missing values with a specified value
* @param value The value to replace NaN with
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, NaN, 6]);
* const sf2 = sf.fillNa(-99);
* console.log(sf2.values);
* //output [ 1, 2, 3, 4, -99, 6 ]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, NaN, 6]);
* sf.fillNa(-99, { inplace: true });
* console.log(sf.values);
* //output [ 1, 2, 3, 4, -99, 6 ]
* ```
*/
fillNa(value: number | string | boolean, options?: { inplace?: boolean }): Series
fillNa(value: number | string | boolean, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (!value && typeof value !== "boolean" && typeof value !== "number") {
throw Error('ParamError: value must be specified');
}
const newValues: ArrayType1D = [];
(this.values as ArrayType1D).forEach((val) => {
if (utils.isEmpty(val)) {
newValues.push(value);
} else {
newValues.push(val);
}
});
if (inplace) {
this.$setValues(newValues)
} else {
return utils.createNdframeFromNewDataWithOldProps({
ndFrame: this,
newData: newValues,
isSeries: true
}) as Series
}
}
/**
* Sort a Series in ascending or descending order by some criterion.
* @param options Method options
* @param ascending Whether to return sorted values in ascending order or not. Defaults to true
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([2, 1, 3, 4, 6, 5]);
* const sf2 = sf.sortValues();
* console.log(sf2.values);
* //output [ 1, 2, 3, 4, 5, 6 ]
* ```
*/
sortValues(options?: { ascending?: boolean, inplace?: boolean }): Series
sortValues(options?: { ascending?: boolean, inplace?: boolean }): Series | void {
const { ascending, inplace, } = { ascending: true, inplace: false, ...options }
let sortedValues = [];
let sortedIndex = []
const rangeIdx = utils.range(0, this.index.length - 1);
let sortedIdx = utils.sortArrayByIndex(rangeIdx, this.values, this.dtypes[0]);
for (let indx of sortedIdx) {
sortedValues.push(this.values[indx])
sortedIndex.push(this.index[indx])
}
if (ascending) {
sortedValues = sortedValues.reverse();
sortedIndex = sortedIndex.reverse();
}
if (inplace) {
this.$setValues(sortedValues as ArrayType1D)
this.$setIndex(sortedIndex);
} else {
const sf = new Series(sortedValues, {
index: sortedIndex,
dtypes: this.dtypes,
config: this.config
});
return sf;
}
}
/**
* Makes a deep copy of a Series
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = sf.copy();
* ```
*
*/
copy(): Series {
const sf = new Series([...this.values], {
columns: [...this.columns],
index: [...this.index],
dtypes: [...this.dtypes],
config: { ...this.config }
});
return sf;
}
/**
* Generate descriptive statistics.
* Descriptive statistics include those that summarize the central tendency,
* dispersion and shape of a dataset’s distribution, excluding NaN values.
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = sf.describe();
* sf2.print();
* ```
*/
describe(): Series {
if (this.dtypes[0] == "string") {
throw new Error("DType Error: Cannot generate descriptive statistics for Series with string dtype")
} else {
const index = ['count', 'mean', 'std', 'min', 'median', 'max', 'variance'];
const count = this.count();
const mean = this.mean();
const std = this.std();
const min = this.min();
const median = this.median();
const max = this.max();
const variance = this.var();
const data = [count, mean, std, min, median, max, variance];
const sf = new Series(data, { index: index });
return sf;
}
}
/**
* Resets the index of the Series to default values.
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.resetIndex();
* console.log(sf2.index);
* //output [ 0, 1, 2, 3, 4, 5 ]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* sf.resetIndex({ inplace: true });
* console.log(sf.index);
* //output [ 0, 1, 2, 3, 4, 5 ]
* ```
*/
resetIndex(options?: { inplace?: boolean }): Series
resetIndex(options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (inplace) {
this.$resetIndex();
} else {
const sf = this.copy();
sf.$resetIndex();
return sf;
}
}
/**
* Set the Series index (row labels) using an array of the same length.
* @param index Array of new index values,
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6], { index: ['a', 'b', 'c', 'd', 'e', 'f'] });
* const sf2 = sf.setIndex(['g', 'h', 'i', 'j', 'k', 'l']);
* console.log(sf2.index);
* //output [ 'g', 'h', 'i', 'j', 'k', 'l' ]
* ```
*/
setIndex(index: Array<number | string | (number | string)>, options?: { inplace?: boolean }): Series
setIndex(index: Array<number | string | (number | string)>, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }
if (!index) {
throw Error('Param Error: Must specify index array');
}
if (inplace) {
this.$setIndex(index)
} else {
const sf = this.copy();
sf.$setIndex(index)
return sf;
}
}
/**
* map all the element in a Series to a function or object.
* @param callable callable can either be a funtion or an object. If function, then each value and the corresponding index is passed.
* @param options.inplace Boolean indicating whether to perform the operation inplace or not. Defaults to false
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = sf.map((x) => x * 2);
* console.log(sf2.values);
* //output [ 2, 4, 6, 8, 10, 12 ]
* ```
*
* @example
* ```
* const sf = new Series([1, 2, 3, 4, 5, 6]);
* const sf2 = sf.map({
* 1: -99,
* 3: -99
* });
* console.log(sf2.values);
* //output [ -99, 2, -99, 4, -99, 6 ]
* ```
*/
map(callable: mapParam, options?: { inplace?: boolean }): Series
map(callable: mapParam, options?: { inplace?: boolean }): Series | void {
const { inplace } = { inplace: false, ...options }