/
data_frame.ts
2294 lines (2182 loc) · 75.2 KB
/
data_frame.ts
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
// Copyright (c) 2020-2022, NVIDIA CORPORATION.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 {MemoryData, MemoryView, Uint8Buffer} from '@rapidsai/cuda';
import {DeviceBuffer, MemoryResource} from '@rapidsai/rmm';
import * as arrow from 'apache-arrow';
import {compareTypes} from 'apache-arrow/visitor/typecomparator';
import {Readable} from 'stream';
import {Column} from './column';
import {ColumnAccessor} from './column_accessor';
import {concat as concatDataFrames} from './dataframe/concat';
import {Join, JoinResult} from './dataframe/join';
import {DataFrameFormatter, DisplayOptions} from './dataframe/print';
import {GroupByMultiple, GroupByMultipleProps, GroupBySingle, GroupBySingleProps} from './groupby';
import {DISPOSER, scope} from './scope';
import {Series} from './series';
import {Table, ToArrowMetadata} from './table';
import {ReadCSVOptions, ReadCSVOptionsCommon, WriteCSVOptions} from './types/csv';
import {
Bool8,
DataType,
FloatingPoint,
FloatTypes,
IndexType,
Int32,
Int64,
Integral,
IntegralTypes,
List,
Numeric,
NumericTypes,
Struct,
} from './types/dtypes';
import {DuplicateKeepOption, NullOrder} from './types/enums';
import {ColumnsMap, CommonType, TypeMap} from './types/mappings';
import {ReadORCOptions, ReadORCOptionsCommon, WriteORCOptions} from './types/orc';
import {ReadParquetOptions, ReadParquetOptionsCommon, WriteParquetOptions} from './types/parquet';
export type SeriesMap<T extends TypeMap = any> = {
[P in keyof T]: {readonly type: T[P]}
};
export type OrderSpec = {
ascending?: boolean,
null_order?: keyof typeof NullOrder
};
type JoinType = 'inner'|'outer'|'left'|'right'|'leftsemi'|'leftanti';
type JoinProps<
Rhs extends TypeMap,
TOn extends string,
How extends JoinType = 'inner',
LSuffix extends string = '',
RSuffix extends string = '',
> = {
other: DataFrame<Rhs>;
on: TOn[];
how?: How;
lsuffix?: LSuffix;
rsuffix?: RSuffix;
nullEquality?: boolean;
memoryResource?: MemoryResource;
};
type CombinedGroupByProps<T extends TypeMap, R extends keyof T, IndexKey extends string> =
GroupBySingleProps<T, R>|Partial<GroupByMultipleProps<T, R, IndexKey>>;
function _seriesToColumns<T extends TypeMap>(data: ColumnsMap<T>|SeriesMap<T>) {
const columns = {} as any;
for (const [name, col] of Object.entries(data)) {
if (col instanceof Series) {
columns[name] = col._col;
} else {
columns[name] = Series.new(col)._col;
}
}
return <ColumnsMap<T>>columns;
}
function _throwIfNonNumeric(type: DataType, operationName: string) {
if (!NumericTypes.some((t) => compareTypes(t, type))) {
throw new TypeError(`dtype ${type.toString()} cannot perform the operation: ${operationName}`);
}
}
/**
* A GPU Dataframe object.
*/
export class DataFrame<T extends TypeMap = any> {
/**
* Construct a DataFrame from a Table and list of column names.
*
* @param table The cudf.Table instance
* @param names List of string Column names
*/
public static fromTable<T extends TypeMap>(table: Table, names: readonly(string&keyof T)[]) {
return new DataFrame(names.reduce(
(map, name, i) => ({...map, [name]: table.getColumnByIndex(i)}), {} as ColumnsMap<T>));
}
/**
* Read a CSV file from disk and create a cudf.DataFrame
*
* @example
* ```typescript
* import * as cudf from '@rapidsai/cudf';
* const df = cudf.DataFrame.readCSV('test.csv', {
* header: 0,
* dataTypes: {
* a: new cudf.Int16,
* b: new cudf.Bool,
* c: new cudf.Float32,
* d: new cudf.Utf8String
* }
* })
* ```
*/
public static readCSV<T extends TypeMap = any>(path: string,
options?: ReadCSVOptionsCommon<T>): DataFrame<T>;
/**
* Read a CSV file from disk and create a cudf.DataFrame
*
* @example
* ```typescript
* import {DataFrame, Series, Int16, Bool, Float32, Utf8String} from '@rapidsai/cudf';
* const df = DataFrame.readCSV({
* header: 0,
* sourceType: 'files',
* sources: ['test.csv'],
* dataTypes: {
* a: new Int16,
* b: new Bool,
* c: new Float32,
* d: new Utf8String
* }
* })
* ```
*/
public static readCSV<T extends TypeMap = any>(options: ReadCSVOptions<T>): DataFrame<T>;
public static readCSV<T extends TypeMap = any>(...args: any[]) {
args = args.flat();
const sources: any[] = args.slice(0, -1);
let options = args[args.length - 1] as ReadCSVOptions<T>| string;
if (typeof options === 'string') {
sources.push(options);
options = {} as ReadCSVOptions<T>;
}
if (sources.length > 0 || !(options && typeof options === 'object')) {
options = {...options, sourceType: 'files', sources};
}
const {names, table} = Table.readCSV(options);
return DataFrame.fromTable<T>(table, names);
}
/**
* Read Apache ORC files from disk and create a cudf.DataFrame
*
* @example
* ```typescript
* import {DataFrame} from '@rapidsai/cudf';
* const df = DataFrame.readORC('test.orc', {
* skipRows: 10, numRows: 10,
* })
* ```
*/
public static readORC<T extends TypeMap = any>(paths: string|(string[]),
options?: ReadORCOptionsCommon): DataFrame<T>;
/**
* Read Apache ORC files from disk and create a cudf.DataFrame
*
* @example
* ```typescript
* import {DataFrame} from '@rapidsai/cudf';
* const df = DataFrame.readORC({
* sourceType: 'files',
* sources: ['test.orc'],
* })
* ```
*/
public static readORC<T extends TypeMap = any>(options: ReadORCOptions): DataFrame<T>;
public static readORC<T extends TypeMap = any>(...args: any[]) {
args = args.flat();
const sources: any[] = args.slice(0, -1);
let options = args[args.length - 1] as ReadORCOptions | string;
if (typeof options === 'string') {
sources.push(options);
options = {} as ReadORCOptions;
}
if (sources.length > 0 || !(options && typeof options === 'object')) {
options = {...options, sourceType: 'files', sources};
}
const {names, table} = Table.readORC(options);
return DataFrame.fromTable<T>(table, names);
}
/**
* Read Apache Parquet files from disk and create a cudf.DataFrame
*
* @example
* ```typescript
* import {DataFrame} from '@rapidsai/cudf';
* const df = DataFrame.readParquet('test.parquet', {
* skipRows: 10, numRows: 10,
* })
* ```
*/
// clang-format off
public static readParquet<T extends TypeMap = any>(paths: string|(string[]),
options?: ReadParquetOptionsCommon): DataFrame<T>;
// clang-format on
/**
* Read Apache Parquet files from disk and create a cudf.DataFrame
*
* @example
* ```typescript
* import {DataFrame} from '@rapidsai/cudf';
* const df = DataFrame.readParquet({
* sourceType: 'files',
* sources: ['test.parquet'],
* })
* ```
*/
public static readParquet<T extends TypeMap = any>(options: ReadParquetOptions): DataFrame<T>;
public static readParquet<T extends TypeMap = any>(...args: any[]) {
args = args.flat();
const sources: any[] = args.slice(0, -1);
let options = args[args.length - 1] as ReadParquetOptions | string;
if (typeof options === 'string') {
sources.push(options);
options = {} as ReadParquetOptions;
}
if (sources.length > 0 || !(options && typeof options === 'object')) {
options = {...options, sourceType: 'files', sources};
}
const {names, table} = Table.readParquet(options);
return DataFrame.fromTable<T>(table, names);
}
/**
* Adapts an Arrow Table in IPC format into a DataFrame.
*
* @param memory A buffer holding Arrow table
* @return The Arrow data as a DataFrame
*/
public static fromArrow<T extends TypeMap>(memory: DeviceBuffer|MemoryData): DataFrame<T> {
if (memory instanceof ArrayBuffer || ArrayBuffer.isView(memory)) {
memory = new Uint8Buffer(memory);
}
if (memory instanceof MemoryView) { memory = memory.buffer; }
const {table, fields} = Table.fromArrow(memory);
const colToSeries = (field: arrow.Field, col: Column): Series<any> => {
return Series.new({
type: field.type,
data: col.data,
offset: col.offset,
length: col.length,
nullMask: col.mask,
nullCount: col.nullCount,
children: (field.type.children as arrow.Field[] ?? [])
.map((f, i) => colToSeries(f, col.getChild(i))),
});
};
return new DataFrame(fields.reduce((seriesMap, f, i) => {
return ({...seriesMap, [f.name]: colToSeries(f, table.getColumnByIndex(i))});
}, {} as SeriesMap<T>));
}
declare private _accessor: ColumnAccessor<T>;
/**
* Create a new cudf.DataFrame
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([1, 2]),
* b: Series.new([true, false]),
* c: Series.new(["foo", "bar"])
* })
*
* ```
*/
constructor(data?: SeriesMap<T>);
constructor(data?: ColumnsMap<T>);
constructor(data?: ColumnAccessor<T>);
constructor(data: any = {}) {
this._accessor =
(data instanceof ColumnAccessor) ? data : new ColumnAccessor(_seriesToColumns(data));
DISPOSER.add(this.asTable());
}
/**
* The number of rows in each column of this DataFrame
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([1, 2]),
* b: Series.new([1, 2]),
* c: Series.new([1, 2])
* })
*
* df.numRows // 2
* ```
*/
get numRows() { return this._accessor.columns.length > 0 ? this._accessor.columns[0].length : 0; }
/**
* The number of columns in this DataFrame
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([1, 2]),
* b: Series.new([1, 2]),
* c: Series.new([1, 2])
* })
*
* df.numColumns // 3
* ```
*/
get numColumns() { return this._accessor.length; }
/**
* The names of columns in this DataFrame
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([1, 2]),
* b: Series.new([1, 2]),
* c: Series.new([1, 2])
* })
*
* df.names // ['a', 'b', 'c']
* ```
*/
get names() { return this._accessor.names; }
/**
* A map of this DataFrame's Series names to their DataTypes
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([1, 2]),
* b: Series.new(["foo", "bar"]),
* c: Series.new([[1, 2], [3]]),
* })
*
* df.types
* // {
* // a: [Object Float64],
* // b: [Object Utf8String],
* // c: [Object List]
* // }
* ```
*/
get types() { return this._accessor.types; }
/** @ignore */
asTable() { return new Table({columns: this._accessor.columns}); }
/** @ignore */
asStruct() {
const {types, _accessor: {columns}} = this;
return Series.new({
nullCount: 0,
children: columns,
length: this.numRows,
type: new Struct(
this.names.map((name, i) => arrow.Field.new(name, types[name], columns[i].nullable))),
});
}
/**
* Return a string with a tabular representation of the DataFrame, pretty-printed according to the
* options given.
*
* @param options
*/
toString(options: DisplayOptions = {}) { return new DataFrameFormatter(options, this).render(); }
[Symbol.for('nodejs.util.inspect.custom')]() {
const [width, maxRows] = process.stdout.getWindowSize();
const rows = this.toString({width, maxRows, maxColWidth: width});
return [
`cols=${this.numColumns.toLocaleString()}, rows=${this.numRows.toLocaleString()}`,
rows,
].join(`\n`);
}
/**
* Return a new DataFrame containing only specified columns.
*
* @param columns Names of columns keep.
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([0, 1, 1, 2, 2, 2]),
* b: Series.new([0, 1, 2, 3, 4, 4]),
* c: Series.new([1, 2, 3, 4, 5, 6])
* })
*
* df.select(['a', 'b']) // returns df with {a, b}
* ```
*/
select<R extends keyof T>(names: readonly R[]) {
return new DataFrame(this._accessor.selectByColumnNames(names));
}
/**
* Return a new DataFrame with new columns added.
*
* @param {SeriesMap<R>|DataFrame<R>} data mapping of names to new columns to add, or a GPU
* DataFrame object
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
*
* const df = new DataFrame({a: [1, 2, 3]});
*
* df.assign({b: Series.new(["foo", "bar", "bar"])})
* // returns df {a: [1, 2, 3], b: ["foo", "bar", "bar"]}
* ```
*
* @example
* ```typescript
* import {DataFrame} from '@rapidsai/cudf';
*
* const df = new DataFrame({a: [1, 2, 3]});
* const df1 = new DataFrame({b: ["foo", "bar", "bar"]});
*
* df.assign(df1) // returns df {a: [1, 2, 3], b: ["foo", "bar", "bar"]}
* ```
*/
assign<R extends TypeMap>(data: SeriesMap<R>|DataFrame<R>) {
const columns = (data instanceof DataFrame) ? data._accessor : _seriesToColumns(data);
return new DataFrame(this._accessor.addColumns(columns));
}
/**
* Return a new DataFrame with specified columns removed.
*
* @param names Names of the columns to drop.
*
* @example
* ```typescript
* import {DataFrame, Series, Int32, Float32} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 1, 2, 2, 2]}),
* b: Series.new({type: new Float32, data: [0, 1, 2, 3, 4, 4]})
* });
*
* df.drop(['a']) // returns df {b: [0, 1, 2, 3, 4, 4]}
* ```
*/
drop<R extends keyof T>(names: readonly R[]) {
return new DataFrame(this._accessor.dropColumns(names));
}
/**
* Return a new DataFrame with specified columns renamed.
*
* @param nameMap Object mapping old to new Column names.
*
* @example
* ```typescript
* import {DataFrame, Series, Int32, Float32} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 1, 2, 2, 2]}),
* b: Series.new({type: new Float32, data: [0, 1, 2, 3, 4, 4]})
* });
*
* df.rename({a: 'c'}) // returns df {b: [0, 1, 2, 3, 4, 4], c: [0, 1, 1, 2, 2, 2]}
* ```
*/
rename<U extends string|number, P extends {[K in keyof T]?: U}>(nameMap: P) {
const names = Object.keys(nameMap) as (string & keyof P)[];
return this.drop(names).assign(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
names.reduce((xs, x) => ({...xs, [`${nameMap[x]!}`]: this.get(x)}),
{} as SeriesMap<{[K in keyof P as `${NonNullable<P[K]>}`]: T[string & K]}>));
}
/**
* Return whether the DataFrame has a Series.
*
* @param name Name of the Series to return.
*
* @example
* ```typescript
* import {DataFrame, Series, Int32, Float32} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 1, 2, 2, 2]}),
* b: Series.new({type: new Float32, data: [0, 1, 2, 3, 4, 4]})
* });
*
* df.has('a') // true
* df.has('c') // false
* ```
*/
has(name: string) { return this._accessor.has(name); }
/**
* Return a series by name.
*
* @param name Name of the Series to return.
*
* @example
* ```typescript
* import {DataFrame, Series, Int32, Float32} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 1, 2, 2, 2]}),
* b: Series.new({type: new Float32, data: [0, 1, 2, 3, 4, 4]})
* });
*
* df.get('a') // Int32Series
* df.get('b') // Float32Series
* ```
*/
get<P extends keyof T>(name: P): Series<T[P]> { return Series.new(this._accessor.get(name)); }
/**
* Casts each selected Series in this DataFrame to a new dtype (similar to `static_cast` in C++).
*
* @param dataTypes The map from column names to new dtypes.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns DataFrame of Series cast to the new dtype
*
* @example
* ```typescript
* import {DataFrame, Series, Int32, Float32} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 1, 2, 2, 2]}),
* b: Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 4]})
* });
*
* df.cast({a: new Float32}); // returns df with a as Float32Series and b as Int32Series
* ```
*/
cast<R extends {[P in keyof T]?: DataType}>(dataTypes: R, memoryResource?: MemoryResource) {
const names = this.names;
const types = !(dataTypes instanceof arrow.DataType)
? dataTypes
: names.reduce((types, name) => ({...types, [name]: dataTypes}), {} as R);
return new DataFrame(names.reduce(
(columns, name) => ({
...columns,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
[name]: name in types ? this.get(name).cast(types[name]!, memoryResource) : this.get(name)
}),
{} as SeriesMap<{[P in keyof(Omit<T, keyof R>& R)]: (Omit<T, keyof R>& R)[P]}>));
}
/**
* Casts all the Series in this DataFrame to a new dtype (similar to `static_cast` in C++).
*
* @param dataType The new dtype.
* @param memoryResource The optional MemoryResource used to allocate the result Series's device
* memory.
* @returns DataFrame of Series cast to the new dtype
*make notebooks.run
* a: Series.new({type: new Int32, data: [0, 1, 1, 2, 2, 2]}),
* b: Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 4]})
* })
*
* df.castAll(new Float32); // returns df with a and b as Float32Series
* ```
*/
castAll<R extends DataType>(dataType: R, memoryResource?: MemoryResource) {
return new DataFrame(this.names.reduce(
(columns, name) => ({...columns, [name]: this.get(name).cast(dataType, memoryResource)}),
{} as SeriesMap<{[P in keyof T]: R}>));
}
/**
* Concat DataFrame(s) to the end of the caller, returning a new DataFrame.
*
* @param others The DataFrame(s) to concat to the end of the caller.
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([1, 2, 3, 4]),
* b: Series.new([1, 2, 3, 4]),
* });
*
* const df2 = new DataFrame({
* a: Series.new([5, 6, 7, 8]),
* });
*
* df.concat(df2);
* // return {
* // a: [1, 2, 3, 4, 5, 6, 7, 8],
* // b: [1, 2, 3, 4, null, null, null, null],
* // }
* ```
*/
concat<U extends DataFrame[]>(...others: U) { return concatDataFrames(this, ...others); }
/**
* @summary Explicitly free the device memory associated with this DataFrame.
*/
dispose() {
this.names.forEach((name) => this.get(name).dispose());
this._accessor = new ColumnAccessor({} as ColumnsMap<T>);
}
/**
* @summary Flatten the elements of this DataFrame's list columns, duplicating the corresponding
* rows for other columns in this DataFrame.
*
* @param {string[]} names Names of List Columns to flatten. Defaults to all list Columns.
* @param {boolean} [includeNulls=true] Whether to retain null entries and map empty lists to
* null.
* @param memoryResource An optional MemoryResource used to allocate the result's device memory.
*/
flatten<R extends string&keyof T>(names: readonly R[] = this.names as any,
includeNulls = true,
memoryResource?: MemoryResource) {
const listColumnIndices =
names.map((n) => [this.types[n], this.names.indexOf(n)] as [DataType, number])
.filter(([t]) => arrow.DataType.isList(t))
.map(([, i]) => i);
type ListChild<T extends DataType> = T extends List ? T['valueType'] : T;
type U = {
// clang-format off
[P in R | keyof T]:
P extends R
? T[P] extends List
? ListChild<T[P]>
: T[P]
: T[P]
// clang-format on
};
return scope(() => {
return listColumnIndices.reduce((df, i, j, a) => {
return scope(() => {
const mr = j === a.length - 1 ? memoryResource : undefined;
const table = includeNulls ? df.asTable().explodeOuter(i, mr) //
: df.asTable().explode(i, mr);
return new DataFrame(df.names.reduce((series_map, name, index) => {
if (index === i) {
series_map[name] =
(this.get(name) as any).elements.__construct(table.getColumnByIndex(index));
} else {
series_map[name] = df.__constructChild(name, table.getColumnByIndex(index));
}
return series_map;
}, {} as SeriesMap<U>));
}, [this]) as any;
}, new DataFrame<U>(this._accessor as any));
}, [this]);
}
/**
* @summary Flatten the elements of this DataFrame's list columns into their positions in its
* original list, duplicating the corresponding rows for other columns in this DataFrame.
*
* @param {string[]} names Names of List Columns to flatten. Defaults to all list Columns.
* @param {boolean} [includeNulls=true] Whether to retain null entries and map empty lists to
* null.
* @param memoryResource An optional MemoryResource used to allocate the result's device memory.
*/
flattenIndices<R extends string&keyof T>(names: readonly R[] = this.names as any,
includeNulls = true,
memoryResource?: MemoryResource) {
const listColumnIndices =
names.map((n) => [this.types[n], this.names.indexOf(n)] as [DataType, number])
.filter(([t]) => arrow.DataType.isList(t))
.map(([, i]) => i);
type U = {
// clang-format off
[P in R | keyof T]:
P extends R
? T[P] extends List
? Int32
: T[P]
: T[P]
// clang-format on
};
return scope(() => {
return listColumnIndices.reduce((df, i, j, a) => {
return scope(() => {
const mr = j === a.length - 1 ? memoryResource : undefined;
const table = includeNulls ? df.asTable().explodeOuterPosition(i, mr) //
: df.asTable().explodePosition(i, mr);
return new DataFrame(df.names.reduce((series_map, name, index) => {
if (index === i) {
series_map[name] = Series.new(table.getColumnByIndex(index));
} else {
series_map[name] =
df.__constructChild(name, table.getColumnByIndex(+(index >= i) + index));
}
return series_map;
}, {} as SeriesMap<U>));
}, [this]) as any;
}, new DataFrame<U>(this._accessor as any));
}, [this]);
}
/**
* @summary Interleave columns of a DataFrame into a single Series.
*
* @param dataType The dtype of the result Series (required if the DataFrame has mixed dtypes).
* @param memoryResource An optional MemoryResource used to allocate the result's device memory.
*
* @returns Series representing a packed row-major matrix of all the source DataFrame's Series.
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
*
* new DataFrame({
* a: Series.new([1, 2, 3]),
* b: Series.new([4, 5, 6]),
* }).interleaveColumns()
* // Float64Series [
* // 1, 4, 2, 5, 3, 6
* // ]
*
* new DataFrame({
* b: Series.new([ [0, 1, 2], [3, 4, 5], [6, 7, 8]]),
* c: Series.new([[10, 11, 12], [13, 14, 15], [16, 17, 18]]),
* }).interleaveColumns()
* // ListSeries [
* // [0, 1, 2],
* // [10, 11, 12],
* // [3, 4, 5],
* // [13, 14, 15],
* // [6, 7, 8],
* // [16, 17, 18],
* // ]
*
*/
interleaveColumns<R extends T[keyof T] = T[keyof T]>(dataType?: R|null,
memoryResource?: MemoryResource) {
return Series.new<R>(
(dataType ? this.castAll(dataType) : this).asTable().interleaveColumns(memoryResource));
}
/**
* Generate an ordering that sorts DataFrame columns in a specified way
*
* @param options mapping of column names to sort order specifications
* @param memoryResource An optional MemoryResource used to allocate the result's device memory.
*
* @returns Series containting the permutation indices for the desired sort order
*
* @example
* ```typescript
* import {DataFrame, Series, Int32, NullOrder} from '@rapidsai/cudf';
* const df = new DataFrame({a: Series.new([null, 4, 3, 2, 1, 0])});
*
* df.orderBy({a: {ascending: true, null_order: 'before'}});
* // Int32Series [0, 5, 4, 3, 2, 1]
*
* df.orderBy({a: {ascending: true, null_order: 'after'}});
* // Int32Series [5, 4, 3, 2, 1, 0]
*
* df.orderBy({a: {ascending: false, null_order: 'before'}});
* // Int32Series [1, 2, 3, 4, 5, 0]
*
* df.orderBy({a: {ascending: false, null_order: 'after'}});
* // Int32Series [0, 1, 2, 3, 4, 5]
* ```
*/
orderBy<R extends keyof T>(options: {[P in R]: OrderSpec}, memoryResource?: MemoryResource) {
const column_orders = new Array<boolean>();
const null_orders = new Array<boolean>();
const columns = new Array<Column<T[keyof T]>>();
const entries = Object.entries(options) as [R, OrderSpec][];
entries.forEach(([name, {ascending = true, null_order = 'after'}]) => {
const child = this.get(name);
if (child) {
columns.push(child._col as Column<T[keyof T]>);
column_orders.push(ascending);
null_orders.push(null_order === 'before');
}
});
// Compute the sorted sorted_indices
return Series.new(new Table({columns}).orderBy(column_orders, null_orders, memoryResource));
}
/**
* Generate a new DataFrame sorted in the specified way.
*
* @param ascending whether to sort ascending (true) or descending (false)
* Default: true
* @param null_order whether nulls should sort before or after other values
* Default: after
*
* @returns A new DataFrame of sorted values
*
* @example
* ```typescript
* import {DataFrame, Series, Int32} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([null, 4, 3, 2, 1, 0]),
* b: Series.new([0, 1, 2, 3, 4, 5])
* });
*
* df.sortValues({a: {ascending: true, null_order: 'after'}})
* // {a: [0, 1, 2, 3, 4, null], b: [5, 4, 3, 2, 1, 0]}
*
* df.sortValues({a: {ascending: true, null_order: 'before'}})
* // {a: [null, 0, 1, 2, 3, 4], b: [0, 5, 4, 3, 2, 1]}
*
* df.sortValues({a: {ascending: false, null_order: 'after'}})
* // {a: [4, 3, 2, 1, 0, null], b: [1, 2, 3, 4, 5, 0]}
*
* df.sortValues({a: {ascending: false, null_order: 'before'}})
* // {a: [null, 4, 3, 2, 1, 0], b: [0, 1, 2, 3, 4, 5]}
* ```
*/
sortValues<R extends keyof T>(options: {[P in R]: OrderSpec}, memoryResource?: MemoryResource) {
return this.gather(this.orderBy(options), false, memoryResource);
}
/**
* @summary Return sub-selection from a DataFrame using the specified integral indices.
*
* @description Gathers the rows of the source columns according to `selection`, such that row "i"
* in the resulting Table's columns will contain row `selection[i]` from the source columns. The
* number of rows in the result table will be equal to the number of elements in selection. A
* negative value i in the selection is interpreted as i+n, where `n` is the number of rows in
* the source table.
*
* For dictionary columns, the keys column component is copied and not trimmed if the gather
* results in abandoned key elements.
*
* @param selection A Series of 8/16/32-bit signed or unsigned integer indices to gather.
* @param nullify_out_of_bounds If `true`, coerce rows that corresponds to out-of-bounds indices
* in the selection to null. If `false`, skips all bounds checking for selection values. Pass
* false if you are certain that the selection contains only valid indices for better
* performance. If `false` and there are out-of-bounds indices in the selection, the behavior
* is undefined. Defaults to `false`.
* @param memoryResource An optional MemoryResource used to allocate the result's device memory.
*
* @example
* ```typescript
* import {DataFrame, Series, Int32} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5]}),
* b: Series.new([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
* });
*
* const selection = Series.new({type: new Int32, data: [2,4,5]});
*
* df.gather(selection); // {a: [2, 4, 5], b: [2.0, 4.0, 5.0]}
* ```
*/
gather<R extends IndexType>(selection: Series<R>,
nullify_out_of_bounds = false,
memoryResource?: MemoryResource) {
const columns = this.asTable().gather(selection._col, nullify_out_of_bounds, memoryResource);
const series_map = {} as SeriesMap<T>;
this.names.forEach((name, index) => {
series_map[name] = this.__constructChild(name, columns.getColumnByIndex(index));
});
return new DataFrame(series_map);
}
/**
* Returns the first n rows as a new DataFrame.
*
* @param n The number of rows to return.
*
* @example
* ```typescript
* import {DataFrame, Series, Int32} from '@rapidsai/cudf';
*
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6]}),
* b: Series.new([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
* });
*
* a.head();
* // {a: [0, 1, 2, 3, 4], b: [0.0, 1.0, 2.0, 3.0, 4.0]}
*
* b.head(1);
* // {a: [0], b: [0.0]}
*
* a.head(-1);
* // throws index out of bounds error
* ```
*/
head(n = 5): DataFrame<T> {
if (n < 0) { throw new Error('Index provided is out of bounds'); }
const selection =
Series.sequence({type: new Int32, size: n < this.numRows ? n : this.numRows, init: 0});
return this.gather(selection);
}
/**
* Returns the last n rows as a new DataFrame.
*
* @param n The number of rows to return.
*
* @example
* ```typescript
* import {DataFrame, Series, Int32} from '@rapidsai/cudf';
*
* const df = new DataFrame({
* a: Series.new({type: new Int32, data: [0, 1, 2, 3, 4, 5, 6]}),
* b: Series.new([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
* });
*
* a.tail();
* // {a: [2, 3, 4, 5, 6], b: [2.0, 3.0, 4.0, 5.0, 6.0]}
*
* b.tail(1);
* // {a: [6], b: [6.0]}
*
* a.tail(-1);
* // throws index out of bounds error
* ```
*/
tail(n = 5): DataFrame<T> {
if (n < 0) { throw new Error('Index provided is out of bounds'); }
const length = n < this.numRows ? n : this.numRows;
const selection = Series.sequence({type: new Int32, size: length, init: this.numRows - length});
return this.gather(selection);
}
/**
* Return a group-by on a single column.
*
* @param props configuration for the groupby
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([0, 1, 1, 2, 2, 2]),
* b: Series.new([0, 1, 2, 3, 4, 4]),
* c: Series.new([1, 2, 3, 4, 5, 6])
* })
*
* df.groupby({by: 'a'}).max() // { a: [2, 1, 0], b: [4, 2, 0], c: [6, 3, 1] }
*
* ```
*/
groupBy<R extends keyof T>(props: GroupBySingleProps<T, R>): GroupBySingle<T, R>;
/**
* Return a group-by on a multiple columns.
*
* @param props configuration for the groupby
*
* @example
* ```typescript
* import {DataFrame, Series} from '@rapidsai/cudf';
* const df = new DataFrame({
* a: Series.new([0, 1, 1, 2, 2, 2]),
* b: Series.new([0, 1, 2, 3, 4, 4]),
* c: Series.new([1, 2, 3, 4, 5, 6])
* })
*
* df.groupby({by: ['a', 'b']}).max()
* // {
* // "a_b": [{"a": [2, 1, 1, 2, 0], "b": [4, 2, 1, 3, 0]}],
* // "c": [6, 3, 2, 4, 1]
* // }
*
* ```
*/