-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.clj
7119 lines (3715 loc) · 113 KB
/
index.clj
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
^:kindly/hide-code
(ns index
(:require [scicloj.kindly.v4.api :as kindly]
[scicloj.kindly.v4.kind :as kind]))
^:kindly/hide-code
(def md
(comp kindly/hide-code kind/md))
(md
"Dataset (data frame) manipulation API for the [tech.ml.dataset](https://github.com/techascent/tech.ml.dataset) library.")
(def tech-ml-version (get-in (read-string (slurp "deps.edn")) [:deps 'techascent/tech.ml.dataset :mvn/version]))
(def tablecloth-version (nth (read-string (slurp "project.clj")) 2))
tech-ml-version
tablecloth-version
(md "
## Introduction
[tech.ml.dataset](https://github.com/techascent/tech.ml.dataset) is a great and fast library which brings columnar dataset to the Clojure. Chris Nuernberger has been working on this library for last year as a part of bigger `tech.ml` stack.
I've started to test the library and help to fix uncovered bugs. My main goal was to compare functionalities with the other standards from other platforms. I focused on R solutions: [dplyr](https://dplyr.tidyverse.org/), [tidyr](https://tidyr.tidyverse.org/) and [data.table](https://rdatatable.gitlab.io/data.table/).
During conversions of the examples I've come up how to reorganized existing `tech.ml.dataset` functions into simple to use API. The main goals were:
* Focus on dataset manipulation functionality, leaving other parts of `tech.ml` like pipelines, datatypes, readers, ML, etc.
* Single entry point for common operations - one function dispatching on given arguments.
* `group-by` results with special kind of dataset - a dataset containing subsets created after grouping as a column.
* Most operations recognize regular dataset and grouped dataset and process data accordingly.
* One function form to enable thread-first on dataset.
If you want to know more about `tech.ml.dataset` and `dtype-next` please refer their documentation:
* [tech.ml.dataset walkthrough](https://techascent.github.io/tech.ml.dataset/walkthrough.html)
* [dtype-next overview](https://cnuernber.github.io/dtype-next/overview.html)
* [dtype-next cheatsheet](https://cnuernber.github.io/dtype-next/cheatsheet.html)
[SOURCE CODE](https://github.com/scicloj/tablecloth)
Join the discussion on [Zulip](https://clojurians.zulipchat.com/#narrow/stream/236259-tech.2Eml.2Edataset.2Edev/topic/api)
First, let's require main namespace and define dataset used in most examples:
")
(require '[tablecloth.api :as tc]
'[tech.v3.datatype.functional :as dfn])
(def DS (tc/dataset {:V1 (take 9 (cycle [1 2]))
:V2 (range 1 10)
:V3 (take 9 (cycle [0.5 1.0 1.5]))
:V4 (take 9 (cycle ["A" "B" "C"]))}))
DS
(md "
## Dataset API
Dataset is a special type which can be considered as a map of columns implemented around `tech.ml.dataset` library. Each column can be considered as named sequence of typed data. Supported types include integers, floats, string, boolean, date/time, objects etc.
### Dataset creation
Dataset can be created from various of types of Clojure structures and files:
* single values
* sequence of maps
* map of sequences or values
* sequence of `tech.v3.dataset.column`s (taken from other dataset or created manually)
* array of any arrays
* file types: raw/gzipped csv/tsv, json, xls(x) taken from local file system or URL
* input stream
`tc/dataset` accepts:
* data
* options (see documentation of `tech.ml.dataset/->dataset` function for full list):
- `:dataset-name` - name of the dataset
- `:num-rows` - number of rows to read from file
- `:header-row?` - indication if first row in file is a header
- `:key-fn` - function applied to column names (eg. `keyword`, to convert column names to keywords)
- `:separator` - column separator
- `:single-value-column-name` - name of the column when single value is provided
- `:column-names` - in case you want to name columns - only works for sequential input (arrays) or empty dataset
- `:layout` - for numerical, native array of arrays - treat entries `:as-rows` or `:as-columns` (default)
`tc/let-dataset` accepts bindings `symbol`-`column-data` to simulate R's `tibble` function. Each binding is converted into a column. You can refer previous columns to in further bindings (as in `let`).
----
Empty dataset.
")
(tc/dataset)
(md "
----
Empty dataset with column names
")
(tc/dataset nil {:column-names [:a :b]})
(md "
----
Dataset created from map (keys = column names, vals = value(s)).
")
(tc/dataset {:A 33})
(tc/dataset {:A [1 2 3]})
(tc/dataset {:A [3 4 5] :B ["X" "Y" "Z"]})
(md "
----
Non-sequential values are repeated row-count number of times.
")
(tc/dataset {:A [1 2 3 4 5 6] :B "X" :C :a})
(md "
----
You can put any value inside a column
")
(tc/dataset {:A [[3 4 5] [:a :b]] :B "X"})
(md "
----
Sequence of maps
")
(tc/dataset [{:a 1 :b 3} {:b 2 :a 99}])
(tc/dataset [{:a 1 :b [1 2 3]} {:a 2 :b [3 4]}])
(md "
----
Missing values are marked by `nil`
")
(tc/dataset [{:a nil :b 1} {:a 3 :b 4} {:a 11}])
(md "
----
Reading from arrays, by default `:as-rows`
")
(tc/dataset [[:a 1] [:b 2] [:c 3]])
(-> (map int-array [[1 2] [3 4] [5 6]])
(into-array)
(tc/dataset))
(md "
`:as-columns`
")
(-> (map int-array [[1 2] [3 4] [5 6]])
(into-array)
(tc/dataset {:layout :as-columns}))
(md "
`:as-rows` with names
")
(-> (map int-array [[1 2] [3 4] [5 6]])
(into-array)
(tc/dataset {:layout :as-rows
:column-names [:a :b]}))
(md "
Any objects
")
(-> (map to-array [[:a :z] ["ee" "ww"] [9 10]])
(into-array)
(tc/dataset {:column-names [:a :b :c]
:layout :as-columns}))
(md "
----
Create dataset using macro `let-dataset` to simulate R `tibble` function. Each binding is converted into a column.
")
(tc/let-dataset [x (range 1 6)
y 1
z (dfn/+ x y)])
(md "
----
Import CSV file
")
(tc/dataset "data/family.csv")
(md "
----
Import from URL
")
(defonce ds (tc/dataset "https://vega.github.io/vega-lite/examples/data/seattle-weather.csv"))
ds
(md "
----
When none of above works, singleton dataset is created. Along with the error message from the exception thrown by `tech.ml.dataset`
")
(tc/dataset 999)
(md "
To see the stack trace, turn it on by setting `:stack-trace?` to `true`.
----
Set column name for single value. Also set the dataset name and turn off creating error message column.
")
(tc/dataset 999 {:single-value-column-name "my-single-value"
:error-column? false})
(tc/dataset 999 {:single-value-column-name ""
:dataset-name "Single value"
:error-column? false})
(md "
### Saving
Export dataset to a file or output stream can be done by calling `tc/write!`. Function accepts:
* dataset
* file name with one of the extensions: `.csv`, `.tsv`, `.csv.gz` and `.tsv.gz` or output stream
* options:
- `:separator` - string or separator char.
")
(tc/write! ds "output.tsv.gz")
(.exists (clojure.java.io/file "output.tsv.gz"))
(md "
#### Nippy
")
(tc/write! DS "output.nippy.gz")
(tc/dataset "output.nippy.gz")
(md "
### Dataset related functions
Summary functions about the dataset like number of rows, columns and basic stats.
----
Number of rows
")
(tc/row-count ds)
(md "
----
Number of columns
")
(tc/column-count ds)
(md "
----
Shape of the dataset, [row count, column count]
")
(tc/shape ds)
(md "
----
General info about dataset. There are three variants:
* default - containing information about columns with basic statistics
- `:basic` - just name, row and column count and information if dataset is a result of `group-by` operation
- `:columns` - columns' metadata
")
(tc/info ds)
(tc/info ds :basic)
(tc/info ds :columns)
(md "
----
Getting a dataset name
")
(tc/dataset-name ds)
(md "
----
Setting a dataset name (operation is immutable).
")
(->> "seattle-weather"
(tc/set-dataset-name ds)
(tc/dataset-name))
(md "
### Columns and rows
Get columns and rows as sequences. `column`, `columns` and `rows` treat grouped dataset as regular one. See `Groups` to read more about grouped datasets.
Possible result types:
- `:as-seq` or `:as-seqs` - sequence of seqences (default)
- `:as-maps` - sequence of maps (rows)
- `:as-map` - map of sequences (columns)
- `:as-double-arrays` - array of double arrays
- `:as-vecs` - sequence of vectors (rows)
For `rows` setting `:nil-missing?` option to `false` will elide keys for nil values.
----
Select column.
")
(ds "wind")
(tc/column ds "date")
(md "
----
Columns as sequence
")
(take 2 (tc/columns ds))
(md "
----
Columns as map
")
(keys (tc/columns ds :as-map))
(md "
----
Rows as sequence of sequences
")
(take 2 (tc/rows ds))
(md "
----
Select rows/columns as double-double-array
")
(-> ds
(tc/select-columns :type/numerical)
(tc/head)
(tc/rows :as-double-arrays))
(-> ds
(tc/select-columns :type/numerical)
(tc/head)
(tc/columns :as-double-arrays))
(md "
----
Rows as sequence of maps
")
(clojure.pprint/pprint (take 2 (tc/rows ds :as-maps)))
(md "
----
Rows with missing values
")
(-> {:a [1 nil 2]
:b [3 4 nil]}
(tc/dataset)
(tc/rows :as-maps))
(md "
Rows with elided missing values
")
(-> {:a [1 nil 2]
:b [3 4 nil]}
(tc/dataset)
(tc/rows :as-maps {:nil-missing? false}))
(md "
### Single entry
Get single value from the table using `get-in` from Clojure API or `get-entry`. First argument is column name, second is row number.
")
(get-in ds ["wind" 2])
(tc/get-entry ds "wind" 2)
(md "
### Printing
Dataset is printed using `dataset->str` or `print-dataset` functions. Options are the same as in `tech.ml.dataset/dataset-data->str`. Most important is `:print-line-policy` which can be one of the: `:single`, `:repl` or `:markdown`.
")
(tc/print-dataset (tc/group-by DS :V1) {:print-line-policy :markdown})
(tc/print-dataset (tc/group-by DS :V1) {:print-line-policy :repl})
(tc/print-dataset (tc/group-by DS :V1) {:print-line-policy :single})
(md "
### Group-by
Grouping by is an operation which splits dataset into subdatasets and pack it into new special type of... dataset. I distinguish two types of dataset: regular dataset and grouped dataset. The latter is the result of grouping.
Grouped dataset is annotated in by `:grouped?` meta tag and consist following columns:
* `:name` - group name or structure
* `:group-id` - integer assigned to the group
* `:data` - groups as datasets
Almost all functions recognize type of the dataset (grouped or not) and operate accordingly.
You can't apply reshaping or join/concat functions on grouped datasets.
#### Grouping
Grouping is done by calling `group-by` function with arguments:
* `ds` - dataset
* `grouping-selector` - what to use for grouping
* options:
- `:result-type` - what to return:
* `:as-dataset` (default) - return grouped dataset
* `:as-indexes` - return rows ids (row number from original dataset)
* `:as-map` - return map with group names as keys and subdataset as values
* `:as-seq` - return sequence of subdatasets
- `:select-keys` - list of the columns passed to a grouping selector function
All subdatasets (groups) have set name as the group name, additionally `group-id` is in meta.
Grouping can be done by:
* single column name
* seq of column names
* map of keys (group names) and row indexes
* value returned by function taking row as map (limited to `:select-keys`)
Note: currently dataset inside dataset is printed recursively so it renders poorly from markdown. So I will use `:as-seq` result type to show just group names and groups.
----
List of columns in grouped dataset
")
(-> DS
(tc/group-by :V1)
(tc/column-names))
(md "
----
List of columns in grouped dataset treated as regular dataset
")
(-> DS
(tc/group-by :V1)
(tc/as-regular-dataset)
(tc/column-names))
(md "
----
Content of the grouped dataset
")
(tc/columns (tc/group-by DS :V1) :as-map)
(md "
----
Grouped dataset as map
")
(keys (tc/group-by DS :V1 {:result-type :as-map}))
(vals (tc/group-by DS :V1 {:result-type :as-map}))
(md "
----
Group dataset as map of indexes (row ids)
")
(tc/group-by DS :V1 {:result-type :as-indexes})
(md "
----
Grouped datasets are printed as follows by default.
")
(tc/group-by DS :V1)
(md "
----
To get groups as sequence or a map can be done from grouped dataset using `groups->seq` and `groups->map` functions.
Groups as seq can be obtained by just accessing `:data` column.
I will use temporary dataset here.
")
(let [ds (-> {"a" [1 1 2 2]
"b" ["a" "b" "c" "d"]}
(tc/dataset)
(tc/group-by "a"))]
(seq (ds :data))) ;; seq is not necessary but Markdown treats `:data` as command here
(-> {"a" [1 1 2 2]
"b" ["a" "b" "c" "d"]}
(tc/dataset)
(tc/group-by "a")
(tc/groups->seq))
(md "
----
Groups as map
")
(-> {"a" [1 1 2 2]
"b" ["a" "b" "c" "d"]}
(tc/dataset)
(tc/group-by "a")
(tc/groups->map))
(md "
----
Grouping by more than one column. You can see that group names are maps. When ungrouping is done these maps are used to restore column names.
")
(tc/group-by DS [:V1 :V3] {:result-type :as-seq})
(md "
----
Grouping can be done by providing just row indexes. This way you can assign the same row to more than one group.
")
(tc/group-by DS {"group-a" [1 2 1 2]
"group-b" [5 5 5 1]} {:result-type :as-seq})
(md "
----
You can group by a result of grouping function which gets row as map and should return group name. When map is used as a group name, ungrouping restore original column names.
")
(tc/group-by DS (fn [row] (* (:V1 row)
(:V3 row))) {:result-type :as-seq})
(md "
----
You can use any predicate on column to split dataset into two groups.
")
(tc/group-by DS (comp #(< % 1.0) :V3) {:result-type :as-seq})
(md "
----
`juxt` is also helpful
")
(tc/group-by DS (juxt :V1 :V3) {:result-type :as-seq})
(md "
----
`tech.ml.dataset` provides an option to limit columns which are passed to grouping functions. It's done for performance purposes.
")
(tc/group-by DS identity {:result-type :as-seq
:select-keys [:V1]})
(md "
#### Ungrouping
Ungrouping simply concats all the groups into the dataset. Following options are possible
* `:order?` - order groups according to the group name ascending order. Default: `false`
* `:add-group-as-column` - should group name become a column? If yes column is created with provided name (or `:$group-name` if argument is `true`). Default: `nil`.
* `:add-group-id-as-column` - should group id become a column? If yes column is created with provided name (or `:$group-id` if argument is `true`). Default: `nil`.
* `:dataset-name` - to name resulting dataset. Default: `nil` (_unnamed)
If group name is a map, it will be splitted into separate columns. Be sure that groups (subdatasets) doesn't contain the same columns already.
If group name is a vector, it will be splitted into separate columns. If you want to name them, set vector of target column names as `:add-group-as-column` argument.
After ungrouping, order of the rows is kept within the groups but groups are ordered according to the internal storage.
----
Grouping and ungrouping.
")
(-> DS
(tc/group-by :V3)
(tc/ungroup))
(md "
----
Groups sorted by group name and named.
")
(-> DS
(tc/group-by :V3)
(tc/ungroup {:order? true
:dataset-name "Ordered by V3"}))
(md "
----
Groups sorted descending by group name and named.
")
(-> DS
(tc/group-by :V3)
(tc/ungroup {:order? :desc
:dataset-name "Ordered by V3 descending"}))
(md "
----
Let's add group name and id as additional columns
")
(-> DS
(tc/group-by (comp #(< % 4) :V2))
(tc/ungroup {:add-group-as-column true
:add-group-id-as-column true}))
(md "
----
Let's assign different column names
")
(-> DS
(tc/group-by (comp #(< % 4) :V2))
(tc/ungroup {:add-group-as-column "Is V2 less than 4?"
:add-group-id-as-column "group id"}))
(md "
----
If we group by map, we can automatically create new columns out of group names.
")
(-> DS
(tc/group-by (fn [row] {"V1 and V3 multiplied" (* (:V1 row)
(:V3 row))
"V4 as lowercase" (clojure.string/lower-case (:V4 row))}))
(tc/ungroup {:add-group-as-column true}))
(md "
----
We can add group names without separation
")
(-> DS
(tc/group-by (fn [row] {"V1 and V3 multiplied" (* (:V1 row)
(:V3 row))
"V4 as lowercase" (clojure.string/lower-case (:V4 row))}))
(tc/ungroup {:add-group-as-column "just map"
:separate? false}))
(md "
----
The same applies to group names as sequences
")
(-> DS
(tc/group-by (juxt :V1 :V3))
(tc/ungroup {:add-group-as-column "abc"}))
(md "
----
Let's provide column names
")
(-> DS
(tc/group-by (juxt :V1 :V3))
(tc/ungroup {:add-group-as-column ["v1" "v3"]}))
(md "
----
Also we can supress separation
")
(-> DS
(tc/group-by (juxt :V1 :V3))
(tc/ungroup {:separate? false
:add-group-as-column true}))
(md "
#### Other functions
To check if dataset is grouped or not just use `grouped?` function.
")
(tc/grouped? DS)
(tc/grouped? (tc/group-by DS :V1))
(md "
----
If you want to remove grouping annotation (to make all the functions work as with regular dataset) you can use `unmark-group` or `as-regular-dataset` (alias) functions.
It can be important when you want to remove some groups (rows) from grouped dataset using `drop-rows` or something like that.
")
(-> DS
(tc/group-by :V1)
(tc/as-regular-dataset)
(tc/grouped?))
(md "
You can also operate on grouped dataset as a regular one in case you want to access its columns using `without-grouping->` threading macro.
")
(-> DS
(tc/group-by [:V4 :V1])
(tc/without-grouping->
(tc/order-by (comp (juxt :V4 :V1) :name))))
(md "
----
This is considered internal.
If you want to implement your own mapping function on grouped dataset you can call `process-group-data` and pass function operating on datasets. Result should be a dataset to have ungrouping working.
")
(-> DS
(tc/group-by :V1)
(tc/process-group-data #(str "Shape: " (vector (tc/row-count %) (tc/column-count %))))
(tc/as-regular-dataset))
(md "
### Columns
Column is a special `tech.ml.dataset` structure. For our purposes we cat treat columns as typed and named sequence bound to particular dataset.
Type of the data is inferred from a sequence during column creation.
#### Names
To select dataset columns or column names `columns-selector` is used. `columns-selector` can be one of the following:
* `:all` keyword - selects all columns
* column name - for single column
* sequence of column names - for collection of columns
* regex - to apply pattern on column names or datatype
* filter predicate - to filter column names or datatype
* `type` namespaced keyword for specific datatype or group of datatypes
Column name can be anything.
`column-names` function returns names according to `columns-selector` and optional `meta-field`. `meta-field` is one of the following:
* `:name` (default) - to operate on column names
* `:datatype` - to operated on column types
* `:all` - if you want to process all metadata
Datatype groups are:
* `:type/numerical` - any numerical type
* `:type/float` - floating point number (`:float32` and `:float64`)
* `:type/integer` - any integer
* `:type/datetime` - any datetime type
If qualified keyword starts with `:!type`, complement set is used.
----
To select all column names you can use `column-names` function.
")
(tc/column-names DS)
(md "
or
")