Liking cljdoc? Tell your friends :D

Introduction

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, tidyr and 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 tech.ml.datatype please refer their documentation:

SOURCE CODE

Join the discussion on Zulip

Let's require main namespace and define dataset used in most examples:

(require '[tablecloth.api :as api])
(def DS (api/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

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Functionality

Dataset

Dataset is a special type which can be considered as a map of columns implemented around tech.ml.datatype 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 columns (taken from other dataset or created manually)
  • sequence of pairs
  • file types: raw/gzipped csv/tsv, json, xls(x) taken from local file system or URL
  • input stream

api/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

Empty dataset.

(api/dataset)
_unnamed [0 0]

Dataset from single value.

(api/dataset 999)

_unnamed [1 1]:

:$value
999

Set column name for single value. Also set the dataset name.

(api/dataset 999 {:single-value-column-name "my-single-value"})
(api/dataset 999 {:single-value-column-name ""
                  :dataset-name "Single value"})

_unnamed [1 1]:

my-single-value
999

Single value [1 1]:

0
999

Sequence of pairs (first = column name, second = value(s)).

(api/dataset [[:A 33] [:B 5] [:C :a]])

_unnamed [1 3]:

:A:B:C
335:a

Not sequential values are repeated row-count number of times.

(api/dataset [[:A [1 2 3 4 5 6]] [:B "X"] [:C :a]])

_unnamed [6 3]:

:A:B:C
1X:a
2X:a
3X:a
4X:a
5X:a
6X:a

Dataset created from map (keys = column names, vals = value(s)). Works the same as sequence of pairs.

(api/dataset {:A 33})
(api/dataset {:A [1 2 3]})
(api/dataset {:A [3 4 5] :B "X"})

_unnamed [1 1]:

:A
33

_unnamed [3 1]:

:A
1
2
3

_unnamed [3 2]:

:A:B
3X
4X
5X

You can put any value inside a column

(api/dataset {:A [[3 4 5] [:a :b]] :B "X"})

_unnamed [2 2]:

:A:B
[3 4 5]X
[:a :b]X

Sequence of maps

(api/dataset [{:a 1 :b 3} {:b 2 :a 99}])
(api/dataset [{:a 1 :b [1 2 3]} {:a 2 :b [3 4]}])

_unnamed [2 2]:

:a:b
13
992

_unnamed [2 2]:

:a:b
1[1 2 3]
2[3 4]

Missing values are marked by nil

(api/dataset [{:a nil :b 1} {:a 3 :b 4} {:a 11}])

_unnamed [3 2]:

:a:b
1
34
11

Import CSV file

(api/dataset "data/family.csv")

data/family.csv [5 5]:

familydob_child1dob_child2gender_child1gender_child2
11998-11-262000-01-2912
21996-06-22 2
32002-07-112004-04-0522
42004-10-102009-08-2711
52000-12-052005-02-2821

Import from URL

(defonce ds (api/dataset "https://vega.github.io/vega-lite/examples/data/seattle-weather.csv"))
ds

https://vega.github.io/vega-lite/examples/data/seattle-weather.csv [1461 6]:

dateprecipitationtemp_maxtemp_minwindweather
2012-01-010.00012.805.0004.700drizzle
2012-01-0210.9010.602.8004.500rain
2012-01-030.800011.707.2002.300rain
2012-01-0420.3012.205.6004.700rain
2012-01-051.3008.9002.8006.100rain
2012-01-062.5004.4002.2002.200rain
2012-01-070.0007.2002.8002.300rain
2012-01-080.00010.002.8002.000sun
2012-01-094.3009.4005.0003.400rain
2012-01-101.0006.1000.60003.400rain
2012-01-110.0006.100-1.1005.100sun
2012-01-120.0006.100-1.7001.900sun
2012-01-130.0005.000-2.8001.300sun
2012-01-144.1004.4000.60005.300snow
2012-01-155.3001.100-3.3003.200snow
2012-01-162.5001.700-2.8005.000snow
2012-01-178.1003.3000.0005.600snow
2012-01-1819.800.000-2.8005.000snow
2012-01-1915.20-1.100-2.8001.600snow
2012-01-2013.507.200-1.1002.300snow
2012-01-213.0008.3003.3008.200rain
2012-01-226.1006.7002.2004.800rain
2012-01-230.0008.3001.1003.600rain
2012-01-248.60010.002.2005.100rain
2012-01-258.1008.9004.4005.400rain

Saving

Export dataset to a file or output stream can be done by calling api/write-csv!. 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.
(api/write-csv! ds "output.tsv.gz")
(.exists (clojure.java.io/file "output.csv.gz"))
nil
false

Dataset related functions

Summary functions about the dataset like number of rows, columns and basic stats.


Number of rows

(api/row-count ds)
1461

Number of columns

(api/column-count ds)
6

Shape of the dataset, [row count, column count]

(api/shape ds)
[1461 6]

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
(api/info ds)
(api/info ds :basic)
(api/info ds :columns)

https://vega.github.io/vega-lite/examples/data/seattle-weather.csv: descriptive-stats [6 10]:

:col-name:datatype:n-valid:n-missing:min:mean:mode:max:standard-deviation:skew
date:packed-local-date146102012-01-012013-12-312015-12-31
precipitation:float32146100.0003.02955.906.6803.506
temp_max:float3214610-1.60016.4435.607.3500.2809
temp_min:float3214610-7.1008.23518.305.023-0.2495
weather:string14610sun
wind:float32146100.40003.2419.5001.4380.8917

https://vega.github.io/vega-lite/examples/data/seattle-weather.csv :basic info [1 4]:

:name:grouped?:rows:columns
https://vega.github.io/vega-lite/examples/data/seattle-weather.csvfalse14616

https://vega.github.io/vega-lite/examples/data/seattle-weather.csv :column info [6 4]:

:name:size:datatype:categorical?
date1461:packed-local-date
precipitation1461:float32
temp_max1461:float32
temp_min1461:float32
wind1461:float32
weather1461:stringtrue

Getting a dataset name

(api/dataset-name ds)
"https://vega.github.io/vega-lite/examples/data/seattle-weather.csv"

Setting a dataset name (operation is immutable).

(->> "seattle-weather"
     (api/set-dataset-name ds)
     (api/dataset-name))
"seattle-weather"

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.


Select column.

(ds "wind")
(api/column ds "date")
#tech.ml.dataset.column<float32>[1461]
wind
[4.700, 4.500, 2.300, 4.700, 6.100, 2.200, 2.300, 2.000, 3.400, 3.400, 5.100, 1.900, 1.300, 5.300, 3.200, 5.000, 5.600, 5.000, 1.600, 2.300, ...]
#tech.ml.dataset.column<packed-local-date>[1461]
date
[2012-01-01, 2012-01-02, 2012-01-03, 2012-01-04, 2012-01-05, 2012-01-06, 2012-01-07, 2012-01-08, 2012-01-09, 2012-01-10, 2012-01-11, 2012-01-12, 2012-01-13, 2012-01-14, 2012-01-15, 2012-01-16, 2012-01-17, 2012-01-18, 2012-01-19, 2012-01-20, ...]

Columns as sequence

(take 2 (api/columns ds))
(#tech.ml.dataset.column<packed-local-date>[1461]
date
[2012-01-01, 2012-01-02, 2012-01-03, 2012-01-04, 2012-01-05, 2012-01-06, 2012-01-07, 2012-01-08, 2012-01-09, 2012-01-10, 2012-01-11, 2012-01-12, 2012-01-13, 2012-01-14, 2012-01-15, 2012-01-16, 2012-01-17, 2012-01-18, 2012-01-19, 2012-01-20, ...] #tech.ml.dataset.column<float32>[1461]
precipitation
[0.000, 10.90, 0.8000, 20.30, 1.300, 2.500, 0.000, 0.000, 4.300, 1.000, 0.000, 0.000, 0.000, 4.100, 5.300, 2.500, 8.100, 19.80, 15.20, 13.50, ...])

Columns as map

(keys (api/columns ds :as-map))
("date" "precipitation" "temp_max" "temp_min" "wind" "weather")

Rows as sequence of sequences

(take 2 (api/rows ds))
([#object[java.time.LocalDate 0x633d658f "2012-01-01"] 0.0 12.8 5.0 4.7 "drizzle"] [#object[java.time.LocalDate 0xf8f8094 "2012-01-02"] 10.9 10.6 2.8 4.5 "rain"])

Rows as sequence of maps

(clojure.pprint/pprint (take 2 (api/rows ds :as-maps)))
({"date" #object[java.time.LocalDate 0x76c72bd3 "2012-01-01"],
  "precipitation" 0.0,
  "temp_min" 5.0,
  "weather" "drizzle",
  "temp_max" 12.8,
  "wind" 4.7}
 {"date" #object[java.time.LocalDate 0x31a73282 "2012-01-02"],
  "precipitation" 10.9,
  "temp_min" 2.8,
  "weather" "rain",
  "temp_max" 10.6,
  "wind" 4.5})

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.

(api/print-dataset (api/group-by DS :V1) {:print-line-policy :markdown})
_unnamed [2 3]:

| :name | :group-id |                                                                                                                                                                                                                                                                                  :data |
|-------|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|     1 |         0 | Group: 1 [5 4]:<br><br>\| :V1 \| :V2 \|    :V3 \| :V4 \|<br>\|-----\|-----\|--------\|-----\|<br>\|   1 \|   1 \| 0.5000 \|   A \|<br>\|   1 \|   3 \|  1.500 \|   C \|<br>\|   1 \|   5 \|  1.000 \|   B \|<br>\|   1 \|   7 \| 0.5000 \|   A \|<br>\|   1 \|   9 \|  1.500 \|   C \| |
|     2 |         1 |                                      Group: 2 [4 4]:<br><br>\| :V1 \| :V2 \|    :V3 \| :V4 \|<br>\|-----\|-----\|--------\|-----\|<br>\|   2 \|   2 \|  1.000 \|   B \|<br>\|   2 \|   4 \| 0.5000 \|   A \|<br>\|   2 \|   6 \|  1.500 \|   C \|<br>\|   2 \|   8 \|  1.000 \|   B \| |
(api/print-dataset (api/group-by DS :V1) {:print-line-policy :repl})
_unnamed [2 3]:

| :name | :group-id |                             :data |
|-------|-----------|-----------------------------------|
|     1 |         0 | Group: 1 [5 4]:                   |
|       |           |                                   |
|       |           | \| :V1 \| :V2 \|    :V3 \| :V4 \| |
|       |           | \|-----\|-----\|--------\|-----\| |
|       |           | \|   1 \|   1 \| 0.5000 \|   A \| |
|       |           | \|   1 \|   3 \|  1.500 \|   C \| |
|       |           | \|   1 \|   5 \|  1.000 \|   B \| |
|       |           | \|   1 \|   7 \| 0.5000 \|   A \| |
|       |           | \|   1 \|   9 \|  1.500 \|   C \| |
|     2 |         1 | Group: 2 [4 4]:                   |
|       |           |                                   |
|       |           | \| :V1 \| :V2 \|    :V3 \| :V4 \| |
|       |           | \|-----\|-----\|--------\|-----\| |
|       |           | \|   2 \|   2 \|  1.000 \|   B \| |
|       |           | \|   2 \|   4 \| 0.5000 \|   A \| |
|       |           | \|   2 \|   6 \|  1.500 \|   C \| |
|       |           | \|   2 \|   8 \|  1.000 \|   B \| |
(api/print-dataset (api/group-by DS :V1) {:print-line-policy :single})
_unnamed [2 3]:

| :name | :group-id |           :data |
|-------|-----------|-----------------|
|     1 |         0 | Group: 1 [5 4]: |
|     2 |         1 | Group: 2 [4 4]: |

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 sequens 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
    (api/group-by :V1)
    (api/column-names))
(:V1 :V2 :V3 :V4)

List of columns in grouped dataset treated as regular dataset

(-> DS
    (api/group-by :V1)
    (api/as-regular-dataset)
    (api/column-names))
(:name :group-id :data)

Content of the grouped dataset

(api/columns (api/group-by DS :V1) :as-map)
{:name #tech.ml.dataset.column<int64>[2]
:name
[1, 2, ], :group-id #tech.ml.dataset.column<int64>[2]
:group-id
[0, 1, ], :data #tech.ml.dataset.column<object>[2]
:data
[Group: 1 [5 4]:

| :V1 | :V2 |    :V3 | :V4 |
|-----|-----|--------|-----|
|   1 |   1 | 0.5000 |   A |
|   1 |   3 |  1.500 |   C |
|   1 |   5 |  1.000 |   B |
|   1 |   7 | 0.5000 |   A |
|   1 |   9 |  1.500 |   C |
, Group: 2 [4 4]:

| :V1 | :V2 |    :V3 | :V4 |
|-----|-----|--------|-----|
|   2 |   2 |  1.000 |   B |
|   2 |   4 | 0.5000 |   A |
|   2 |   6 |  1.500 |   C |
|   2 |   8 |  1.000 |   B |
, ]}

Grouped dataset as map

(keys (api/group-by DS :V1 {:result-type :as-map}))
(1 2)
(vals (api/group-by DS :V1 {:result-type :as-map}))

(Group: 1 [5 4]:

:V1:V2:V3:V4
110.5000A
131.500C
151.000B
170.5000A
191.500C

Group: 2 [4 4]:

:V1:V2:V3:V4
221.000B
240.5000A
261.500C
281.000B

)


Group dataset as map of indexes (row ids)

(api/group-by DS :V1 {:result-type :as-indexes})
{1 [0 2 4 6 8], 2 [1 3 5 7]}

Grouped datasets are printed as follows by default.

(api/group-by DS :V1)

_unnamed [2 3]:

:name:group-id:data
10Group: 1 [5 4]:
21Group: 2 [4 4]:

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"]}
             (api/dataset)
             (api/group-by "a"))]
  (seq (ds :data))) ;; seq is not necessary but Markdown treats `:data` as command here

(Group: 1 [2 2]:

ab
1a
1b

Group: 2 [2 2]:

ab
2c
2d

)

(-> {"a" [1 1 2 2]
     "b" ["a" "b" "c" "d"]}
    (api/dataset)
    (api/group-by "a")
    (api/groups->seq))

(Group: 1 [2 2]:

ab
1a
1b

Group: 2 [2 2]:

ab
2c
2d

)


Groups as map

(-> {"a" [1 1 2 2]
     "b" ["a" "b" "c" "d"]}
    (api/dataset)
    (api/group-by "a")
    (api/groups->map))

{1 Group: 1 [2 2]:

ab
1a
1b

, 2 Group: 2 [2 2]:

ab
2c
2d

}


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.

(api/group-by DS [:V1 :V3] {:result-type :as-seq})

(Group: {:V3 1.0, :V1 1} [1 4]:

:V1:V2:V3:V4
151.000B

Group: {:V3 0.5, :V1 1} [2 4]:

:V1:V2:V3:V4
110.5000A
170.5000A

Group: {:V3 0.5, :V1 2} [1 4]:

:V1:V2:V3:V4
240.5000A

Group: {:V3 1.0, :V1 2} [2 4]:

:V1:V2:V3:V4
221.000B
281.000B

Group: {:V3 1.5, :V1 1} [2 4]:

:V1:V2:V3:V4
131.500C
191.500C

Group: {:V3 1.5, :V1 2} [1 4]:

:V1:V2:V3:V4
261.500C

)


Grouping can be done by providing just row indexes. This way you can assign the same row to more than one group.

(api/group-by DS {"group-a" [1 2 1 2]
                  "group-b" [5 5 5 1]} {:result-type :as-seq})

(Group: group-a [4 4]:

:V1:V2:V3:V4
221.000B
131.500C
221.000B
131.500C

Group: group-b [4 4]:

:V1:V2:V3:V4
261.500C
261.500C
261.500C
221.000B

)


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.

(api/group-by DS (fn [row] (* (:V1 row)
                             (:V3 row))) {:result-type :as-seq})

(Group: 1.0 [2 4]:

:V1:V2:V3:V4
240.5000A
151.000B

Group: 2.0 [2 4]:

:V1:V2:V3:V4
221.000B
281.000B

Group: 0.5 [2 4]:

:V1:V2:V3:V4
110.5000A
170.5000A

Group: 3.0 [1 4]:

:V1:V2:V3:V4
261.500C

Group: 1.5 [2 4]:

:V1:V2:V3:V4
131.500C
191.500C

)


You can use any predicate on column to split dataset into two groups.

(api/group-by DS (comp #(< % 1.0) :V3) {:result-type :as-seq})

(Group: false [6 4]:

:V1:V2:V3:V4
221.000B
131.500C
151.000B
261.500C
281.000B
191.500C

Group: true [3 4]:

:V1:V2:V3:V4
110.5000A
240.5000A
170.5000A

)


juxt is also helpful

(api/group-by DS (juxt :V1 :V3) {:result-type :as-seq})

(Group: [1 1.0] [1 4]:

:V1:V2:V3:V4
151.000B

Group: [1 0.5] [2 4]:

:V1:V2:V3:V4
110.5000A
170.5000A

Group: [2 1.5] [1 4]:

:V1:V2:V3:V4
261.500C

Group: [1 1.5] [2 4]:

:V1:V2:V3:V4
131.500C
191.500C

Group: [2 0.5] [1 4]:

:V1:V2:V3:V4
240.5000A

Group: [2 1.0] [2 4]:

:V1:V2:V3:V4
221.000B
281.000B

)


tech.ml.dataset provides an option to limit columns which are passed to grouping functions. It's done for performance purposes.

(api/group-by DS identity {:result-type :as-seq
                           :select-keys [:V1]})

(Group: {:V1 1} [5 4]:

:V1:V2:V3:V4
110.5000A
131.500C
151.000B
170.5000A
191.500C

Group: {:V1 2} [4 4]:

:V1:V2:V3:V4
221.000B
240.5000A
261.500C
281.000B

)

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
    (api/group-by :V3)
    (api/ungroup))

_unnamed [9 4]:

:V1:V2:V3:V4
221.000B
151.000B
281.000B
110.5000A
240.5000A
170.5000A
131.500C
261.500C
191.500C

Groups sorted by group name and named.

(-> DS
    (api/group-by :V3)
    (api/ungroup {:order? true
                  :dataset-name "Ordered by V3"}))

Ordered by V3 [9 4]:

:V1:V2:V3:V4
110.5000A
240.5000A
170.5000A
221.000B
151.000B
281.000B
131.500C
261.500C
191.500C

Groups sorted descending by group name and named.

(-> DS
    (api/group-by :V3)
    (api/ungroup {:order? :desc
                  :dataset-name "Ordered by V3 descending"}))

Ordered by V3 descending [9 4]:

:V1:V2:V3:V4
131.500C
261.500C
191.500C
221.000B
151.000B
281.000B
110.5000A
240.5000A
170.5000A

Let's add group name and id as additional columns

(-> DS
    (api/group-by (comp #(< % 4) :V2))
    (api/ungroup {:add-group-as-column true
                  :add-group-id-as-column true}))

_unnamed [9 6]:

:$group-name:$group-id:V1:V2:V3:V4
false0240.5000A
false0151.000B
false0261.500C
false0170.5000A
false0281.000B
false0191.500C
true1110.5000A
true1221.000B
true1131.500C

Let's assign different column names

(-> DS
    (api/group-by (comp #(< % 4) :V2))
    (api/ungroup {:add-group-as-column "Is V2 less than 4?"
                  :add-group-id-as-column "group id"}))

_unnamed [9 6]:

Is V2 less than 4?group id:V1:V2:V3:V4
false0240.5000A
false0151.000B
false0261.500C
false0170.5000A
false0281.000B
false0191.500C
true1110.5000A
true1221.000B
true1131.500C

If we group by map, we can automatically create new columns out of group names.

(-> DS
    (api/group-by (fn [row] {"V1 and V3 multiplied" (* (:V1 row)
                                                      (:V3 row))
                            "V4 as lowercase" (clojure.string/lower-case (:V4 row))}))
    (api/ungroup {:add-group-as-column true}))

_unnamed [9 6]:

V1 and V3 multipliedV4 as lowercase:V1:V2:V3:V4
1.000a240.5000A
0.5000a110.5000A
0.5000a170.5000A
1.000b151.000B
2.000b221.000B
2.000b281.000B
3.000c261.500C
1.500c131.500C
1.500c191.500C

We can add group names without separation

(-> DS
    (api/group-by (fn [row] {"V1 and V3 multiplied" (* (:V1 row)
                                                      (:V3 row))
                            "V4 as lowercase" (clojure.string/lower-case (:V4 row))}))
    (api/ungroup {:add-group-as-column "just map"
                  :separate? false}))

_unnamed [9 5]:

just map:V1:V2:V3:V4
{"V1 and V3 multiplied" 1.0, "V4 as lowercase" "a"}240.5000A
{"V1 and V3 multiplied" 0.5, "V4 as lowercase" "a"}110.5000A
{"V1 and V3 multiplied" 0.5, "V4 as lowercase" "a"}170.5000A
{"V1 and V3 multiplied" 1.0, "V4 as lowercase" "b"}151.000B
{"V1 and V3 multiplied" 2.0, "V4 as lowercase" "b"}221.000B
{"V1 and V3 multiplied" 2.0, "V4 as lowercase" "b"}281.000B
{"V1 and V3 multiplied" 3.0, "V4 as lowercase" "c"}261.500C
{"V1 and V3 multiplied" 1.5, "V4 as lowercase" "c"}131.500C
{"V1 and V3 multiplied" 1.5, "V4 as lowercase" "c"}191.500C

The same applies to group names as sequences

(-> DS
    (api/group-by (juxt :V1 :V3))
    (api/ungroup {:add-group-as-column "abc"}))

_unnamed [9 6]:

:abc-0:abc-1:V1:V2:V3:V4
11.000151.000B
10.5000110.5000A
10.5000170.5000A
21.500261.500C
11.500131.500C
11.500191.500C
20.5000240.5000A
21.000221.000B
21.000281.000B

Let's provide column names

(-> DS
    (api/group-by (juxt :V1 :V3))
    (api/ungroup {:add-group-as-column ["v1" "v3"]}))

_unnamed [9 6]:

v1v3:V1:V2:V3:V4
11.000151.000B
10.5000110.5000A
10.5000170.5000A
21.500261.500C
11.500131.500C
11.500191.500C
20.5000240.5000A
21.000221.000B
21.000281.000B

Also we can supress separation

(-> DS
    (api/group-by (juxt :V1 :V3))
    (api/ungroup {:separate? false
                  :add-group-as-column true}))
;; => _unnamed [9 5]:

_unnamed [9 5]:

:$group-name:V1:V2:V3:V4
[1 1.0]151.000B
[1 0.5]110.5000A
[1 0.5]170.5000A
[2 1.5]261.500C
[1 1.5]131.500C
[1 1.5]191.500C
[2 0.5]240.5000A
[2 1.0]221.000B
[2 1.0]281.000B

Other functions

To check if dataset is grouped or not just use grouped? function.

(api/grouped? DS)
nil
(api/grouped? (api/group-by DS :V1))
true

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
    (api/group-by :V1)
    (api/as-regular-dataset)
    (api/grouped?))
nil

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
    (api/group-by :V1)
    (api/process-group-data #(str "Shape: " (vector (api/row-count %) (api/column-count %))))
    (api/as-regular-dataset))

_unnamed [2 3]:

:name:group-id:data
10Shape: [5 4]
21Shape: [4 4]

Columns

Column is a special tech.ml.dataset structure based on tech.ml.datatype library. 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

To select all column names you can use column-names function.

(api/column-names DS)
(:V1 :V2 :V3 :V4)

or

(api/column-names DS :all)
(:V1 :V2 :V3 :V4)

In case you want to select column which has name :all (or is sequence or map), put it into a vector. Below code returns empty sequence since there is no such column in the dataset.

(api/column-names DS [:all])
()

Obviously selecting single name returns it's name if available

(api/column-names DS :V1)
(api/column-names DS "no such column")
(:V1)
()

Select sequence of column names.

(api/column-names DS [:V1 "V2" :V3 :V4 :V5])
(:V1 :V3 :V4)

Select names based on regex, columns ends with 1 or 4

(api/column-names DS #".*[14]")
(:V1 :V4)

Select names based on regex operating on type of the column (to check what are the column types, call (api/info DS :columns). Here we want to get integer columns only.

(api/column-names DS #"^:int.*" :datatype)
(:V1 :V2)

or

(api/column-names DS :type/integer)
(:V1 :V2)

And finally we can use predicate to select names. Let's select double precision columns.

(api/column-names DS #{:float64} :datatype)
(:V3)

or

(api/column-names DS :type/float64 :datatype)
(:V3)

If you want to select all columns but given, use complement function. Works only on a predicate.

(api/column-names DS (complement #{:V1}))
(api/column-names DS (complement #{:float64}) :datatype)
(:V2 :V3 :V4)
(:V1 :V2 :V4)

You can select column names based on all column metadata at once by using :all metadata selector. Below we want to select column names ending with 1 which have long datatype.

(api/column-names DS (fn [meta]
                       (and (= :int64 (:datatype meta))
                            (clojure.string/ends-with? (:name meta) "1"))) :all)
(:V1)

Select

select-columns creates dataset with columns selected by columns-selector as described above. Function works on regular and grouped dataset.


Select only float64 columns

(api/select-columns DS #(= :float64 %) :datatype)

_unnamed [9 1]:

:V3
0.5000
1.000
1.500
0.5000
1.000
1.500
0.5000
1.000
1.500

Select all but :V1 columns

(api/select-columns DS (complement #{:V1}))

_unnamed [9 3]:

:V2:V3:V4
10.5000A
21.000B
31.500C
40.5000A
51.000B
61.500C
70.5000A
81.000B
91.500C

If we have grouped data set, column selection is applied to every group separately.

(-> DS
    (api/group-by :V1)
    (api/select-columns [:V2 :V3])
    (api/groups->map))

{1 Group: 1 [5 2]:

:V2:V3
10.5000
31.500
51.000
70.5000
91.500

, 2 Group: 2 [4 2]:

:V2:V3
21.000
40.5000
61.500
81.000

}

Drop

drop-columns creates dataset with removed columns.


Drop float64 columns

(api/drop-columns DS #(= :float64 %) :datatype)

_unnamed [9 3]:

:V1:V2:V4
11A
22B
13C
24A
15B
26C
17A
28B
19C

Drop all columns but :V1 and :V2

(api/drop-columns DS (complement #{:V1 :V2}))

_unnamed [9 2]:

:V1:V2
11
22
13
24
15
26
17
28
19

If we have grouped data set, column selection is applied to every group separately. Selected columns are dropped.

(-> DS
    (api/group-by :V1)
    (api/drop-columns [:V2 :V3])
    (api/groups->map))

{1 Group: 1 [5 2]:

:V1:V4
1A
1C
1B
1A
1C

, 2 Group: 2 [4 2]:

:V1:V4
2B
2A
2C
2B

}

Rename

If you want to rename colums use rename-columns and pass map where keys are old names, values new ones.

You can also pass mapping function with optional columns-selector

(api/rename-columns DS {:V1 "v1"
                        :V2 "v2"
                        :V3 [1 2 3]
                        :V4 (Object.)})

_unnamed [9 4]:

v1v2[1 2 3]java.lang.Object@24700331
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Map all names with function

(api/rename-columns DS (comp str second name))

_unnamed [9 4]:

1234
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Map selected names with function

(api/rename-columns DS [:V1 :V3] (comp str second name))

_unnamed [9 4]:

1:V23:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Function works on grouped dataset

(-> DS
    (api/group-by :V1)
    (api/rename-columns {:V1 "v1"
                         :V2 "v2"
                         :V3 [1 2 3]
                         :V4 (Object.)})
    (api/groups->map))

{1 Group: 1 [5 4]:

v1v2[1 2 3]java.lang.Object@caf7fbd
110.5000A
131.500C
151.000B
170.5000A
191.500C

, 2 Group: 2 [4 4]:

v1v2[1 2 3]java.lang.Object@caf7fbd
221.000B
240.5000A
261.500C
281.000B

}

Add or update

To add (or replace existing) column call add-or-replace-column function. Function accepts:

  • ds - a dataset
  • column-name - if it's existing column name, column will be replaced
  • column - can be column (from other dataset), sequence, single value or function. Too big columns are always trimmed. Too small are cycled or extended with missing values (according to size-strategy argument)
  • size-strategy (optional) - when new column is shorter than dataset row count, following strategies are applied:
    • :cycle (default) - repeat data
    • :na - append missing values
    • :strict - throws an exception when sizes mismatch

Function works on grouped dataset.


Add single value as column

(api/add-or-replace-column DS :V5 "X")

_unnamed [9 5]:

:V1:V2:V3:V4:V5
110.5000AX
221.000BX
131.500CX
240.5000AX
151.000BX
261.500CX
170.5000AX
281.000BX
191.500CX

Replace one column (column is trimmed)

(api/add-or-replace-column DS :V1 (repeatedly rand))

_unnamed [9 4]:

:V1:V2:V3:V4
0.576810.5000A
0.0185221.000B
0.106631.500C
0.0532340.5000A
0.122951.000B
0.438461.500C
0.171570.5000A
0.692081.000B
0.983891.500C

Copy column

(api/add-or-replace-column DS :V5 (DS :V1))

_unnamed [9 5]:

:V1:V2:V3:V4:V5
110.5000A1
221.000B2
131.500C1
240.5000A2
151.000B1
261.500C2
170.5000A1
281.000B2
191.500C1

When function is used, argument is whole dataset and the result should be column, sequence or single value

(api/add-or-replace-column DS :row-count api/row-count) 

_unnamed [9 5]:

:V1:V2:V3:V4:row-count
110.5000A9
221.000B9
131.500C9
240.5000A9
151.000B9
261.500C9
170.5000A9
281.000B9
191.500C9

Above example run on grouped dataset, applies function on each group separately.

(-> DS
    (api/group-by :V1)
    (api/add-or-replace-column :row-count api/row-count)
    (api/ungroup))

_unnamed [9 5]:

:V1:V2:V3:V4:row-count
110.5000A5
131.500C5
151.000B5
170.5000A5
191.500C5
221.000B4
240.5000A4
261.500C4
281.000B4

When column which is added is longer than row count in dataset, column is trimmed. When column is shorter, it's cycled or missing values are appended.

(api/add-or-replace-column DS :V5 [:r :b])

_unnamed [9 5]:

:V1:V2:V3:V4:V5
110.5000A:r
221.000B:b
131.500C:r
240.5000A:b
151.000B:r
261.500C:b
170.5000A:r
281.000B:b
191.500C:r
(api/add-or-replace-column DS :V5 [:r :b] :na)

_unnamed [9 5]:

:V1:V2:V3:V4:V5
110.5000A:r
221.000B:b
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Exception is thrown when :strict strategy is used and column size is not equal row count

(try
  (api/add-or-replace-column DS :V5 [:r :b] :strict)
  (catch Exception e (str "Exception caught: "(ex-message e))))
"Exception caught: Column size (2) should be exactly the same as dataset row count (9)"

Tha same applies for grouped dataset

(-> DS
    (api/group-by :V3)
    (api/add-or-replace-column :V5 [:r :b] :na)
    (api/ungroup))

_unnamed [9 5]:

:V1:V2:V3:V4:V5
221.000B:r
151.000B:b
281.000B
110.5000A:r
240.5000A:b
170.5000A
131.500C:r
261.500C:b
191.500C

Let's use other column to fill groups

(-> DS
    (api/group-by :V3)
    (api/add-or-replace-column :V5 (DS :V2))
    (api/ungroup))

_unnamed [9 5]:

:V1:V2:V3:V4:V5
221.000B1
151.000B2
281.000B3
110.5000A1
240.5000A2
170.5000A3
131.500C1
261.500C2
191.500C3

In case you want to add or update several columns you can call add-or-replace-columns and provide map where keys are column names, vals are columns.

(api/add-or-replace-columns DS {:V1 #(map inc (% :V1))
                               :V5 #(map (comp keyword str) (% :V4))
                               :V6 11})

_unnamed [9 6]:

:V1:V2:V3:V4:V5:V6
210.5000A:A11
321.000B:B11
231.500C:C11
340.5000A:A11
251.000B:B11
361.500C:C11
270.5000A:A11
381.000B:B11
291.500C:C11

Update

If you want to modify specific column(s) you can call update-columns. Arguments:

  • dataset
  • one of:
    • columns-selector and function (or sequence of functions)
    • map where keys are column names and vals are function

Functions accept column and have to return column or sequence


Reverse of columns

(api/update-columns DS :all reverse) 

_unnamed [9 4]:

:V1:V2:V3:V4
191.500C
281.000B
170.5000A
261.500C
151.000B
240.5000A
131.500C
221.000B
110.5000A

Apply dec/inc on numerical columns

(api/update-columns DS :type/numerical [(partial map dec)
                                        (partial map inc)])

_unnamed [9 4]:

:V1:V2:V3:V4
02-0.5000A
130.000B
040.5000C
15-0.5000A
060.000B
170.5000C
08-0.5000A
190.000B
0100.5000C

You can also assing function to a column by packing operations into the map.

(api/update-columns DS {:V1 reverse
                        :V2 (comp shuffle seq)})

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
261.000B
181.500C
250.5000A
171.000B
291.500C
130.5000A
241.000B
121.500C

Map

The other way of creating or updating column is to map rows as regular map function. The arity of mapping function should be the same as number of selected columns.

Arguments:

  • ds - dataset
  • column-name - target column name
  • columns-selector - columns selected
  • map-fn - mapping function

Let's add numerical columns together

(api/map-columns DS
                 :sum-of-numbers
                 (api/column-names DS  #{:int64 :float64} :datatype)
                 (fn [& rows]
                   (reduce + rows)))

_unnamed [9 5]:

:V1:V2:V3:V4:sum-of-numbers
110.5000A2.500
221.000B5.000
131.500C5.500
240.5000A6.500
151.000B7.000
261.500C9.500
170.5000A8.500
281.000B11.00
191.500C11.50

The same works on grouped dataset

(-> DS
    (api/group-by :V4)
    (api/map-columns :sum-of-numbers
                     (api/column-names DS  #{:int64 :float64} :datatype)
                     (fn [& rows]
                       (reduce + rows)))
    (api/ungroup))

_unnamed [9 5]:

:V1:V2:V3:V4:sum-of-numbers
110.5000A2.500
240.5000A6.500
170.5000A8.500
221.000B5.000
151.000B7.000
281.000B11.00
131.500C5.500
261.500C9.500
191.500C11.50

Reorder

To reorder columns use columns selectors to choose what columns go first. The unseleted columns are appended to the end.

(api/reorder-columns DS :V4 [:V3 :V2] :V1)

_unnamed [9 4]:

:V4:V2:V3:V1
A10.50001
B21.0002
C31.5001
A40.50002
B51.0001
C61.5002
A70.50001
B81.0002
C91.5001

This function doesn't let you select meta field, so you have to call column-names in such case. Below we want to add integer columns at the end.

(api/reorder-columns DS (api/column-names DS (complement #{:int64}) :datatype))

_unnamed [9 4]:

:V3:V4:V1:V2
0.5000A11
1.000B22
1.500C13
0.5000A24
1.000B15
1.500C26
0.5000A17
1.000B28
1.500C19

Type conversion

To convert column into given datatype can be done using convert-types function. Not all the types can be converted automatically also some types require slow parsing (every conversion from string). In case where conversion is not possible you can pass conversion function.

Arguments:

  • ds - dataset
  • Two options:
    • coltype-map in case when you want to convert several columns, keys are column names, vals are new types
    • column-selector and new-types - column name and new datatype (or datatypes as sequence)

new-types can be:

  • a type like :int64 or :string or sequence of types
  • or sequence of pair of datetype and conversion function

After conversion additional infomation is given on problematic values.

The other conversion is casting column into java array (->array) of the type column or provided as argument. Grouped dataset returns sequence of arrays.


Basic conversion

(-> DS
    (api/convert-types :V1 :float64)
    (api/info :columns))

_unnamed :column info [4 6]:

:name:size:datatype:unparsed-indexes:unparsed-data:categorical?
:V19:float64{}[]
:V29:int64
:V39:float64
:V49:string true

Using custom converter. Let's treat :V4 as haxadecimal values. See that this way we can map column to any value.

(-> DS
    (api/convert-types :V4 [[:int16 #(Integer/parseInt % 16)]]))

_unnamed [9 4]:

:V1:V2:V3:V4
110.500010
221.00011
131.50012
240.500010
151.00011
261.50012
170.500010
281.00011
191.50012

You can process several columns at once

(-> DS
    (api/convert-types {:V1 :float64
                        :V2 :object
                        :V3 [:boolean #(< % 1.0)]
                        :V4 :object})
    (api/info :columns))

_unnamed :column info [4 5]:

:name:size:datatype:unparsed-indexes:unparsed-data
:V19:float64{}[]
:V29:object{}[]
:V39:boolean{}[]
:V49:object

Convert one type into another

(-> DS
    (api/convert-types :type/numerical :int16)
    (api/info :columns))

_unnamed :column info [4 6]:

:name:size:datatype:unparsed-indexes:unparsed-data:categorical?
:V19:int16{}[]
:V29:int16{}[]
:V39:int16{}[]
:V49:string true

Function works on the grouped dataset

(-> DS
    (api/group-by :V1)
    (api/convert-types :V1 :float32)
    (api/ungroup)
    (api/info :columns))

_unnamed :column info [4 6]:

:name:size:datatype:unparsed-indexes:unparsed-data:categorical?
:V19:float32{}[]
:V29:int64
:V39:float64
:V49:string true

Double array conversion.

(api/->array DS :V1)
#object["[J" 0x175a13c3 "[J@175a13c3"]

Function also works on grouped dataset

(-> DS
    (api/group-by :V3)
    (api/->array :V2))
(#object["[J" 0x1da68c92 "[J@1da68c92"] #object["[J" 0x5bd056b7 "[J@5bd056b7"] #object["[J" 0x55a82ab3 "[J@55a82ab3"])

You can also cast the type to the other one (if casting is possible):

(api/->array DS :V4 :string)
(api/->array DS :V1 :float32)
#object["[Ljava.lang.String;" 0x7a87a2fc "[Ljava.lang.String;@7a87a2fc"]
#object["[F" 0x61830cf9 "[F@61830cf9"]

Rows

Rows can be selected or dropped using various selectors:

  • row id(s) - row index as number or seqence of numbers (first row has index 0, second 1 and so on)
  • sequence of true/false values
  • filter by predicate (argument is row as a map)

When predicate is used you may want to limit columns passed to the function (select-keys option).

Additionally you may want to precalculate some values which will be visible for predicate as additional columns. It's done internally by calling add-or-replace-columns on a dataset. :pre is used as a column definitions.

Select

Select fourth row

(api/select-rows DS 4)

_unnamed [1 4]:

:V1:V2:V3:V4
151.000B

Select 3 rows

(api/select-rows DS [1 4 5])

_unnamed [3 4]:

:V1:V2:V3:V4
221.000B
151.000B
261.500C

Select rows using sequence of true/false values

(api/select-rows DS [true nil nil true])

_unnamed [2 4]:

:V1:V2:V3:V4
110.5000A
240.5000A

Select rows using predicate

(api/select-rows DS (comp #(< % 1) :V3))

_unnamed [3 4]:

:V1:V2:V3:V4
110.5000A
240.5000A
170.5000A

The same works on grouped dataset, let's select first row from every group.

(-> DS
    (api/group-by :V1)
    (api/select-rows 0)
    (api/ungroup))

_unnamed [2 4]:

:V1:V2:V3:V4
110.5000A
221.000B

If you want to select :V2 values which are lower than or equal mean in grouped dataset you have to precalculate it using :pre.

(-> DS
    (api/group-by :V4)
    (api/select-rows (fn [row] (<= (:V2 row) (:mean row)))
                     {:pre {:mean #(tech.v2.datatype.functional/mean (% :V2))}})
    (api/ungroup))

_unnamed [6 4]:

:V1:V2:V3:V4
110.5000A
240.5000A
221.000B
151.000B
131.500C
261.500C

Drop

drop-rows removes rows, and accepts exactly the same parameters as select-rows


Drop values lower than or equal :V2 column mean in grouped dataset.

(-> DS
    (api/group-by :V4)
    (api/drop-rows (fn [row] (<= (:V2 row) (:mean row)))
                   {:pre {:mean #(tech.v2.datatype.functional/mean (% :V2))}})
    (api/ungroup))

_unnamed [3 4]:

:V1:V2:V3:V4
170.5000A
281.000B
191.500C

Other

There are several function to select first, last, random rows, or display head, tail of the dataset. All functions work on grouped dataset.

All random functions accept :seed as an option if you want to fix returned result.


First row

(api/first DS)

_unnamed [1 4]:

:V1:V2:V3:V4
110.5000A

Last row

(api/last DS)

_unnamed [1 4]:

:V1:V2:V3:V4
191.500C

Random row (single)

(api/rand-nth DS)

_unnamed [1 4]:

:V1:V2:V3:V4
191.500C

Random row (single) with seed

(api/rand-nth DS {:seed 42})

_unnamed [1 4]:

:V1:V2:V3:V4
261.500C

Random n (default: row count) rows with repetition.

(api/random DS)

_unnamed [9 4]:

:V1:V2:V3:V4
191.500C
281.000B
151.000B
221.000B
131.500C
221.000B
261.500C
151.000B
261.500C

Five random rows with repetition

(api/random DS 5)

_unnamed [5 4]:

:V1:V2:V3:V4
240.5000A
261.500C
240.5000A
170.5000A
261.500C

Five random, non-repeating rows

(api/random DS 5 {:repeat? false})

_unnamed [5 4]:

:V1:V2:V3:V4
110.5000A
221.000B
261.500C
170.5000A
240.5000A

Five random, with seed

(api/random DS 5 {:seed 42})

_unnamed [5 4]:

:V1:V2:V3:V4
261.500C
151.000B
131.500C
110.5000A
191.500C

Shuffle dataset

(api/shuffle DS)

_unnamed [9 4]:

:V1:V2:V3:V4
281.000B
131.500C
170.5000A
110.5000A
151.000B
221.000B
240.5000A
261.500C
191.500C

Shuffle with seed

(api/shuffle DS {:seed 42})

_unnamed [9 4]:

:V1:V2:V3:V4
151.000B
221.000B
261.500C
240.5000A
281.000B
131.500C
170.5000A
110.5000A
191.500C

First n rows (default 5)

(api/head DS)

_unnamed [5 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B

Last n rows (default 5)

(api/tail DS)

_unnamed [5 4]:

:V1:V2:V3:V4
151.000B
261.500C
170.5000A
281.000B
191.500C

by-rank calculates rank on column(s). It's base on R rank() with addition of :dense (default) tie strategy which give consecutive rank numbering.

:desc? options (default: true) sorts input with descending order, giving top values under 0 value.

rank is zero based and is defined at tablecloth.api.utils namespace.


(api/by-rank DS :V3 zero?) ;; most V3 values

_unnamed [3 4]:

:V1:V2:V3:V4
131.500C
261.500C
191.500C
(api/by-rank DS :V3 zero? {:desc? false}) ;; least V3 values

_unnamed [3 4]:

:V1:V2:V3:V4
110.5000A
240.5000A
170.5000A

Rank also works on multiple columns

(api/by-rank DS [:V1 :V3] zero? {:desc? false})

_unnamed [2 4]:

:V1:V2:V3:V4
110.5000A
170.5000A

Select 5 random rows from each group

(-> DS
    (api/group-by :V4)
    (api/random 5)
    (api/ungroup))

_unnamed [15 4]:

:V1:V2:V3:V4
240.5000A
170.5000A
110.5000A
170.5000A
110.5000A
221.000B
151.000B
151.000B
151.000B
221.000B
131.500C
131.500C
191.500C
131.500C
261.500C

Aggregate

Aggregating is a function which produces single row out of dataset.

Aggregator is a function or sequence or map of functions which accept dataset as an argument and result single value, sequence of values or map.

Where map is given as an input or result, keys are treated as column names.

Grouped dataset is ungrouped after aggreation. This can be turned off by setting :ungroup to false. In case you want to pass additional ungrouping parameters add them to the options.

By default resulting column names are prefixed with summary prefix (set it with :default-column-name-prefix option).


Let's calculate mean of some columns

(api/aggregate DS #(reduce + (% :V2)))

_unnamed [1 1]:

:summary
45

Let's give resulting column a name.

(api/aggregate DS {:sum-of-V2 #(reduce + (% :V2))})

_unnamed [1 1]:

:sum-of-V2
45

Sequential result is spread into separate columns

(api/aggregate DS #(take 5(% :V2)))

_unnamed [1 5]:

:summary-0:summary-1:summary-2:summary-3:summary-4
12345

You can combine all variants and rename default prefix

(api/aggregate DS [#(take 3 (% :V2))
                   (fn [ds] {:sum-v1 (reduce + (ds :V1))
                            :prod-v3 (reduce * (ds :V3))})] {:default-column-name-prefix "V2-value"})

_unnamed [1 5]:

:V2-value-0-0:V2-value-0-1:V2-value-0-2:V2-value-1-sum-v1:V2-value-1-prod-v3
123130.4219

Processing grouped dataset

(-> DS
    (api/group-by [:V4])
    (api/aggregate [#(take 3 (% :V2))
                    (fn [ds] {:sum-v1 (reduce + (ds :V1))
                             :prod-v3 (reduce * (ds :V3))})] {:default-column-name-prefix "V2-value"}))

_unnamed [3 6]:

:V4:V2-value-0-0:V2-value-0-1:V2-value-0-2:V2-value-1-sum-v1:V2-value-1-prod-v3
B25851.000
C36943.375
A14740.1250

Result of aggregating is automatically ungrouped, you can skip this step by stetting :ungroup option to false.

(-> DS
    (api/group-by [:V3])
    (api/aggregate [#(take 3 (% :V2))
                    (fn [ds] {:sum-v1 (reduce + (ds :V1))
                             :prod-v3 (reduce * (ds :V3))})] {:default-column-name-prefix "V2-value"
                                                              :ungroup? false}))

_unnamed [3 3]:

:name:group-id:data
{:V3 1.0}0_unnamed [1 5]:
{:V3 0.5}1_unnamed [1 5]:
{:V3 1.5}2_unnamed [1 5]:

Column

You can perform columnar aggreagation also. aggregate-columns selects columns and apply aggregating function (or sequence of functions) for each column separately.

(api/aggregate-columns DS [:V1 :V2 :V3] #(reduce + %))

_unnamed [1 3]:

:V1:V2:V3
13459.000

(api/aggregate-columns DS [:V1 :V2 :V3] [#(reduce + %)
                                         #(reduce max %)
                                         #(reduce * %)])

_unnamed [1 3]:

:V1:V2:V3
1390.4219

(-> DS
    (api/group-by [:V4])
    (api/aggregate-columns [:V1 :V2 :V3] #(reduce + %)))

_unnamed [3 4]:

:V4:V1:V2:V3
B5153.000
C4184.500
A4121.500

Order

Ordering can be done by column(s) or any function operating on row. Possible order can be:

  • :asc for ascending order (default)
  • :desc for descending order
  • custom comparator

:select-keys limits row map provided to ordering functions.


Order by single column, ascending

(api/order-by DS :V1)

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
131.500C
151.000B
170.5000A
191.500C
261.500C
240.5000A
281.000B
221.000B

Descending order

(api/order-by DS :V1 :desc)

_unnamed [9 4]:

:V1:V2:V3:V4
221.000B
240.5000A
261.500C
281.000B
151.000B
131.500C
170.5000A
110.5000A
191.500C

Order by two columns

(api/order-by DS [:V1 :V2])

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
131.500C
151.000B
170.5000A
191.500C
221.000B
240.5000A
261.500C
281.000B

Use different orders for columns

(api/order-by DS [:V1 :V2] [:asc :desc])

_unnamed [9 4]:

:V1:V2:V3:V4
191.500C
170.5000A
151.000B
131.500C
110.5000A
281.000B
261.500C
240.5000A
221.000B
(api/order-by DS [:V1 :V2] [:desc :desc])

_unnamed [9 4]:

:V1:V2:V3:V4
281.000B
261.500C
240.5000A
221.000B
191.500C
170.5000A
151.000B
131.500C
110.5000A
(api/order-by DS [:V1 :V3] [:desc :asc])

_unnamed [9 4]:

:V1:V2:V3:V4
240.5000A
221.000B
281.000B
261.500C
110.5000A
170.5000A
151.000B
131.500C
191.500C

Custom function can be used to provied ordering key. Here order by :V4 descending, then by product of other columns ascending.

(api/order-by DS [:V4 (fn [row] (* (:V1 row)
                                  (:V2 row)
                                  (:V3 row)))] [:desc :asc] {:select-keys [:V1 :V2 :V3]})

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
170.5000A
240.5000A
221.000B
131.500C
151.000B
191.500C
281.000B
261.500C

Custom comparator also can be used in case objects are not comparable by default. Let's define artificial one: if Euclidean distance is lower than 2, compare along z else along x and y. We use first three columns for that.

(defn dist
  [v1 v2]
  (->> v2
       (map - v1)
       (map #(* % %))
       (reduce +)
       (Math/sqrt)))
#'user/dist
(api/order-by DS [:V1 :V2 :V3] (fn [[x1 y1 z1 :as v1] [x2 y2 z2 :as v2]]
                                 (let [d (dist v1 v2)]
                                   (if (< d 2.0)
                                     (compare z1 z2)
                                     (compare [x1 y1] [x2 y2])))))

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
151.000B
170.5000A
191.500C
221.000B
240.5000A
131.500C
261.500C
281.000B

Unique

Remove rows which contains the same data. By default unique-by removes duplicates from whole dataset. You can also pass list of columns or functions (similar as in group-by) to remove duplicates limited by them. Default strategy is to keep the first row. More strategies below.

unique-by works on groups


Remove duplicates from whole dataset

(api/unique-by DS)

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Remove duplicates from each group selected by column.

(api/unique-by DS :V1)

_unnamed [2 4]:

:V1:V2:V3:V4
110.5000A
221.000B

Pair of columns

(api/unique-by DS [:V1 :V3])

_unnamed [6 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C

Also function can be used, split dataset by modulo 3 on columns :V2

(api/unique-by DS (fn [m] (mod (:V2 m) 3)))

_unnamed [3 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C

The same can be achived with group-by

(-> DS
    (api/group-by (fn [m] (mod (:V2 m) 3)))
    (api/first)
    (api/ungroup))

_unnamed [3 4]:

:V1:V2:V3:V4
131.500C
110.5000A
221.000B

Grouped dataset

(-> DS
    (api/group-by :V4)
    (api/unique-by :V1)
    (api/ungroup))

_unnamed [6 4]:

:V1:V2:V3:V4
110.5000A
240.5000A
221.000B
151.000B
131.500C
261.500C

Strategies

There are 4 strategies defined:

  • :first - select first row (default)
  • :last - select last row
  • :random - select random row
  • any function - apply function to a columns which are subject of uniqueness

Last

(api/unique-by DS :V1 {:strategy :last})

_unnamed [2 4]:

:V1:V2:V3:V4
281.000B
191.500C

Random

(api/unique-by DS :V1 {:strategy :random})

_unnamed [2 4]:

:V1:V2:V3:V4
110.5000A
281.000B

Pack columns into vector

(api/unique-by DS :V4 {:strategy vec})

_unnamed [3 3]:

:V1:V2:V3
[2 1 2][2 5 8][1.0 1.0 1.0]
[1 2 1][3 6 9][1.5 1.5 1.5]
[1 2 1][1 4 7][0.5 0.5 0.5]

Sum columns

(api/unique-by DS :V4 {:strategy (partial reduce +)})

_unnamed [3 3]:

:V1:V2:V3
5153.000
4184.500
4121.500

Group by function and apply functions

(api/unique-by DS (fn [m] (mod (:V2 m) 3)) {:strategy vec})

_unnamed [3 4]:

:V1:V2:V3:V4
[1 2 1][3 6 9][1.5 1.5 1.5]["C" "C" "C"]
[1 2 1][1 4 7][0.5 0.5 0.5]["A" "A" "A"]
[2 1 2][2 5 8][1.0 1.0 1.0]["B" "B" "B"]

Grouped dataset

(-> DS
    (api/group-by :V1)
    (api/unique-by (fn [m] (mod (:V2 m) 3)) {:strategy vec})
    (api/ungroup {:add-group-as-column :from-V1}))

_unnamed [6 5]:

:from-V1:V1:V2:V3:V4
1[1 1][3 9][1.5 1.5]["C" "C"]
1[1 1][1 7][0.5 0.5]["A" "A"]
1[1][5][1.0]["B"]
2[2][6][1.5]["C"]
2[2][4][0.5]["A"]
2[2 2][2 8][1.0 1.0]["B" "B"]

Missing

When dataset contains missing values you can select or drop rows with missing values or replace them using some strategy.

column-selector can be used to limit considered columns

Let's define dataset which contains missing values

(def DSm (api/dataset {:V1 (take 9 (cycle [1 2 nil]))
                       :V2 (range 1 10)
                       :V3 (take 9 (cycle [0.5 1.0 nil 1.5]))
                       :V4 (take 9 (cycle ["A" "B" "C"]))}))
DSm

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
221.000B
3 C
141.500A
250.5000B
61.000C
17 A
281.500B
90.5000C

Select

Select rows with missing values

(api/select-missing DSm)

_unnamed [4 4]:

:V1:V2:V3:V4
3 C
61.000C
17 A
90.5000C

Select rows with missing values in :V1

(api/select-missing DSm :V1)

_unnamed [3 4]:

:V1:V2:V3:V4
3 C
61.000C
90.5000C

The same with grouped dataset

(-> DSm
    (api/group-by :V4)
    (api/select-missing :V3)
    (api/ungroup))

_unnamed [2 4]:

:V1:V2:V3:V4
17 A
3 C

Drop

Drop rows with missing values

(api/drop-missing DSm)

_unnamed [5 4]:

:V1:V2:V3:V4
110.5000A
221.000B
141.500A
250.5000B
281.500B

Drop rows with missing values in :V1

(api/drop-missing DSm :V1)

_unnamed [6 4]:

:V1:V2:V3:V4
110.5000A
221.000B
141.500A
250.5000B
17 A
281.500B

The same with grouped dataset

(-> DSm
    (api/group-by :V4)
    (api/drop-missing :V1)
    (api/ungroup))

_unnamed [6 4]:

:V1:V2:V3:V4
110.5000A
141.500A
17 A
221.000B
250.5000B
281.500B

Replace

Missing values can be replaced using several strategies. replace-missing accepts:

  • dataset
  • column selector
  • value
    • single value
    • sequence of values (cycled)
    • function, applied on column(s) with stripped missings
  • strategy (optional)

Strategies are:

  • :value - replace with given value (default)
  • :up - copy values up
  • :down - copy values down

Let's define special dataset here:

(def DSm2 (api/dataset {:a [nil nil nil 1.0 2   nil 4   nil  11 nil nil]
                        :b [2.0   2   2 nil nil 3   nil   3  4  5 5]}))
DSm2

_unnamed [11 2]:

:a:b
2.000
2.000
2.000
1.000
2.000
3.000
4.000
3.000
11.004.000
5.000
5.000

Replace missing with single value in whole dataset

(api/replace-missing DSm2 999)

_unnamed [11 2]:

:a:b
999.02.000
999.02.000
999.02.000
1.000999.0
2.000999.0
999.03.000
4.000999.0
999.03.000
11.004.000
999.05.000
999.05.000

Replace missing with single value in :a column

(api/replace-missing DSm2 :a 999)

_unnamed [11 2]:

:a:b
999.02.000
999.02.000
999.02.000
1.000
2.000
999.03.000
4.000
999.03.000
11.004.000
999.05.000
999.05.000

Replace missing with sequence in :a column

(api/replace-missing DSm2 :a [-999 -998 -997])

_unnamed [11 2]:

:a:b
-999.02.000
-998.02.000
-997.02.000
1.000
2.000
-999.03.000
4.000
-998.03.000
11.004.000
-997.05.000
-999.05.000

Replace missing with a function (mean)

(api/replace-missing DSm2 :a tech.v2.datatype.functional/mean)

_unnamed [11 2]:

:a:b
4.5002.000
4.5002.000
4.5002.000
1.000
2.000
4.5003.000
4.000
4.5003.000
11.004.000
4.5005.000
4.5005.000

Using :down strategy, fills gaps with values from above. You can see that if missings are at the beginning, they are left missing.

(api/replace-missing DSm2 [:a :b] nil :down)

_unnamed [11 2]:

:a:b
2.000
2.000
2.000
1.0002.000
2.0002.000
2.0003.000
4.0003.000
4.0003.000
11.004.000
11.005.000
11.005.000

To fix above issue you can provide value

(api/replace-missing DSm2 [:a :b] 999 :down)

_unnamed [11 2]:

:a:b
999.02.000
999.02.000
999.02.000
1.0002.000
2.0002.000
2.0003.000
4.0003.000
4.0003.000
11.004.000
11.005.000
11.005.000

The same applies for :up strategy which is opposite direction.

(api/replace-missing DSm2 [:a :b] 999 :up)

_unnamed [11 2]:

:a:b
1.0002.000
1.0002.000
1.0002.000
1.0003.000
2.0003.000
4.0003.000
4.0003.000
11.003.000
11.004.000
999.05.000
999.05.000

We can use a function which is applied after applying :up or :down

(api/replace-missing DSm2 [:a :b] tech.v2.datatype.functional/mean :down)

_unnamed [11 2]:

:a:b
4.5002.000
4.5002.000
4.5002.000
1.0002.000
2.0002.000
2.0003.000
4.0003.000
4.0003.000
11.004.000
11.005.000
11.005.000

Join/Separate Columns

Joining or separating columns are operations which can help to tidy messy dataset.

  • join-columns joins content of the columns (as string concatenation or other structure) and stores it in new column
  • separate-column splits content of the columns into set of new columns

Join

join-columns accepts:

  • dataset
  • column selector (as in select-columns)
  • options
    • :separator (default "-")
    • :drop-columns? - whether to drop source columns or not (default true)
    • :result-type
      • :map - packs data into map
      • :seq - packs data into sequence
      • :string - join strings with separator (default)
      • or custom function which gets row as a vector
    • :missing-subst - substitution for missing value

Default usage. Create :joined column out of other columns.

(api/join-columns DSm :joined [:V1 :V2 :V4])

_unnamed [9 2]:

:V3:joined
0.50001-1-A
1.0002-2-B
3-C
1.5001-4-A
0.50002-5-B
1.0006-C
1-7-A
1.5002-8-B
0.50009-C

Without dropping source columns.

(api/join-columns DSm :joined [:V1 :V2 :V4] {:drop-columns? false})

_unnamed [9 5]:

:V1:V2:V3:V4:joined
110.5000A1-1-A
221.000B2-2-B
3 C3-C
141.500A1-4-A
250.5000B2-5-B
61.000C6-C
17 A1-7-A
281.500B2-8-B
90.5000C9-C

Let's replace missing value with "NA" string.

(api/join-columns DSm :joined [:V1 :V2 :V4] {:missing-subst "NA"})

_unnamed [9 2]:

:V3:joined
0.50001-1-A
1.0002-2-B
NA-3-C
1.5001-4-A
0.50002-5-B
1.000NA-6-C
1-7-A
1.5002-8-B
0.5000NA-9-C

We can use custom separator.

(api/join-columns DSm :joined [:V1 :V2 :V4] {:separator "/"
                                             :missing-subst "."})

_unnamed [9 2]:

:V3:joined
0.50001/1/A
1.0002/2/B
./3/C
1.5001/4/A
0.50002/5/B
1.000./6/C
1/7/A
1.5002/8/B
0.5000./9/C

Or even sequence of separators.

(api/join-columns DSm :joined [:V1 :V2 :V4] {:separator ["-" "/"]
                                             :missing-subst "."})

_unnamed [9 2]:

:V3:joined
0.50001-1/A
1.0002-2/B
.-3/C
1.5001-4/A
0.50002-5/B
1.000.-6/C
1-7/A
1.5002-8/B
0.5000.-9/C

The other types of results, map:

(api/join-columns DSm :joined [:V1 :V2 :V4] {:result-type :map})

_unnamed [9 2]:

:V3:joined
0.5000{:V1 1, :V2 1, :V4 "A"}
1.000{:V1 2, :V2 2, :V4 "B"}
{:V1 nil, :V2 3, :V4 "C"}
1.500{:V1 1, :V2 4, :V4 "A"}
0.5000{:V1 2, :V2 5, :V4 "B"}
1.000{:V1 nil, :V2 6, :V4 "C"}
{:V1 1, :V2 7, :V4 "A"}
1.500{:V1 2, :V2 8, :V4 "B"}
0.5000{:V1 nil, :V2 9, :V4 "C"}

Sequence

(api/join-columns DSm :joined [:V1 :V2 :V4] {:result-type :seq})

_unnamed [9 2]:

:V3:joined
0.5000(1 1 "A")
1.000(2 2 "B")
(nil 3 "C")
1.500(1 4 "A")
0.5000(2 5 "B")
1.000(nil 6 "C")
(1 7 "A")
1.500(2 8 "B")
0.5000(nil 9 "C")

Custom function, calculate hash

(api/join-columns DSm :joined [:V1 :V2 :V4] {:result-type hash})

_unnamed [9 2]:

:V3:joined
0.5000535226087
1.0001128801549
-1842240303
1.5002022347171
0.50001884312041
1.000-1555412370
1640237355
1.500-967279152
0.50001128367958

Grouped dataset

(-> DSm
    (api/group-by :V4)
    (api/join-columns :joined [:V1 :V2 :V4])
    (api/ungroup))

_unnamed [9 2]:

:V3:joined
0.50001-1-A
1.5001-4-A
1-7-A
1.0002-2-B
0.50002-5-B
1.5002-8-B
3-C
1.0006-C
0.50009-C

Tidyr examples

source

(def df (api/dataset {:x ["a" "a" nil nil]
                      :y ["b" nil "b" nil]}))
#'user/df
df

_unnamed [4 2]:

:x:y
ab
a
b

(api/join-columns df "z" [:x :y] {:drop-columns? false
                                  :missing-subst "NA"
                                  :separator "_"})

_unnamed [4 3]:

:x:yz
aba_b
a a_NA
bNA_b
NA_NA

(api/join-columns df "z" [:x :y] {:drop-columns? false
                                  :separator "_"})

_unnamed [4 3]:

:x:yz
aba_b
a a
bb

Separate

Column can be also separated into several other columns using string as separator, regex or custom function. Arguments:

  • dataset
  • source column
  • target columns
  • separator as:
    • string - it's converted to regular expression and passed to clojure.string/split function
    • regex
    • or custom function (default: identity)
  • options
    • :drop-columns? - whether drop source column or not (default: true)
    • :missing-subst - values which should be treated as missing, can be set, sequence, value or function (default: "")

Custom function (as separator) should return seqence of values for given value.


Separate float into integer and factional values

(api/separate-column DS :V3 [:int-part :frac-part] (fn [^double v]
                                                     [(int (quot v 1.0))
                                                      (mod v 1.0)]))

_unnamed [9 5]:

:V1:V2:int-part:frac-part:V4
1100.5000A
2210.000B
1310.5000C
2400.5000A
1510.000B
2610.5000C
1700.5000A
2810.000B
1910.5000C

Source column can be kept

(api/separate-column DS :V3 [:int-part :frac-part] (fn [^double v]
                                                     [(int (quot v 1.0))
                                                      (mod v 1.0)]) {:drop-column? false})

_unnamed [9 6]:

:V1:V2:V3:int-part:frac-part:V4
110.500000.5000A
221.00010.000B
131.50010.5000C
240.500000.5000A
151.00010.000B
261.50010.5000C
170.500000.5000A
281.00010.000B
191.50010.5000C

We can treat 0 or 0.0 as missing value

(api/separate-column DS :V3 [:int-part :frac-part] (fn [^double v]
                                                     [(int (quot v 1.0))
                                                      (mod v 1.0)]) {:missing-subst [0 0.0]})

_unnamed [9 5]:

:V1:V2:int-part:frac-part:V4
11 0.5000A
221 B
1310.5000C
24 0.5000A
151 B
2610.5000C
17 0.5000A
281 B
1910.5000C

Works on grouped dataset

(-> DS
    (api/group-by :V4)
    (api/separate-column :V3 [:int-part :fract-part] (fn [^double v]
                                                       [(int (quot v 1.0))
                                                        (mod v 1.0)]))
    (api/ungroup))

_unnamed [9 5]:

:V1:V2:int-part:fract-part:V4
1100.5000A
2400.5000A
1700.5000A
2210.000B
1510.000B
2810.000B
1310.5000C
2610.5000C
1910.5000C

Join and separate together.

(-> DSm
    (api/join-columns :joined [:V1 :V2 :V4] {:result-type :map})
    (api/separate-column :joined [:v1 :v2 :v4] (juxt :V1 :V2 :V4)))

_unnamed [9 4]:

:V3:v1:v2:v4
0.500011A
1.00022B
3C
1.50014A
0.500025B
1.000 6C
17A
1.50028B
0.5000 9C
(-> DSm
    (api/join-columns :joined [:V1 :V2 :V4] {:result-type :seq})
    (api/separate-column :joined [:v1 :v2 :v4] identity))

_unnamed [9 4]:

:V3:v1:v2:v4
0.500011A
1.00022B
3C
1.50014A
0.500025B
1.000 6C
17A
1.50028B
0.5000 9C
Tidyr examples

separate source extract source

(def df-separate (api/dataset {:x [nil "a.b" "a.d" "b.c"]}))
(def df-separate2 (api/dataset {:x ["a" "a b" nil "a b c"]}))
(def df-separate3 (api/dataset {:x ["a?b" nil "a.b" "b:c"]}))
(def df-extract (api/dataset {:x [nil "a-b" "a-d" "b-c" "d-e"]}))
#'user/df-separate
#'user/df-separate2
#'user/df-separate3
#'user/df-extract
df-separate

_unnamed [4 1]:

:x
a.b
a.d
b.c
df-separate2

_unnamed [4 1]:

:x
a
a b
a b c
df-separate3

_unnamed [4 1]:

:x
a?b
a.b
b:c
df-extract

_unnamed [5 1]:

:x
a-b
a-d
b-c
d-e

(api/separate-column df-separate :x [:A :B] "\\.")

_unnamed [4 2]:

:A:B
ab
ad
bc

You can drop columns after separation by setting nil as a name. We need second value here.

(api/separate-column df-separate :x [nil :B] "\\.")

_unnamed [4 1]:

:B
b
d
c

Extra data is dropped

(api/separate-column df-separate2 :x ["a" "b"] " ")

_unnamed [4 2]:

ab
a
ab
ab

Split with regular expression

(api/separate-column df-separate3 :x ["a" "b"] "[?\\.:]")

_unnamed [4 2]:

ab
ab
ab
bc

Or just regular expression to extract values

(api/separate-column df-separate3 :x ["a" "b"] #"(.).(.)")

_unnamed [4 2]:

ab
ab
ab
bc

Extract first value only

(api/separate-column df-extract :x ["A"] "-")

_unnamed [5 1]:

A
a
a
b
d

Split with regex

(api/separate-column df-extract :x ["A" "B"] #"(\p{Alnum})-(\p{Alnum})")

_unnamed [5 2]:

AB
ab
ad
bc
de

Only a,b,c,d strings

(api/separate-column df-extract :x ["A" "B"] #"([a-d]+)-([a-d]+)")

_unnamed [5 2]:

AB
ab
ad
bc

Fold/Unroll Rows

To pack or unpack the data into single value you can use fold-by and unroll functions.

fold-by groups dataset and packs columns data from each group separately into desired datastructure (like vector or sequence). unroll does the opposite.

Fold-by

Group-by and pack columns into vector

(api/fold-by DS [:V3 :V4 :V1])

_unnamed [6 4]:

:V4:V3:V1:V2
B1.0001[5]
C1.5002[6]
C1.5001[3 9]
A0.50001[1 7]
B1.0002[2 8]
A0.50002[4]

You can pack several columns at once.

(api/fold-by DS [:V4])

_unnamed [3 4]:

:V4:V1:V2:V3
B[2 1 2][2 5 8][1.0 1.0 1.0]
C[1 2 1][3 6 9][1.5 1.5 1.5]
A[1 2 1][1 4 7][0.5 0.5 0.5]

You can use custom packing function

(api/fold-by DS [:V4] seq)

_unnamed [3 4]:

:V4:V1:V2:V3
Bclojure.lang.LazySeq@7c02clojure.lang.LazySeq@7c84clojure.lang.LazySeq@1f0745f
Cclojure.lang.LazySeq@785fclojure.lang.LazySeq@8065clojure.lang.LazySeq@20f8745f
Aclojure.lang.LazySeq@785fclojure.lang.LazySeq@78a3clojure.lang.LazySeq@c3e0745f

or

(api/fold-by DS [:V4] set)

_unnamed [3 4]:

:V4:V1:V2:V3
B#{1 2}#{2 5 8}#{1.0}
C#{1 2}#{6 3 9}#{1.5}
A#{1 2}#{7 1 4}#{0.5}

This works also on grouped dataset

(-> DS
    (api/group-by :V1)
    (api/fold-by :V4)
    (api/ungroup))

_unnamed [6 4]:

:V4:V1:V2:V3
B[1][5][1.0]
C[1 1][3 9][1.5 1.5]
A[1 1][1 7][0.5 0.5]
B[2 2][2 8][1.0 1.0]
C[2][6][1.5]
A[2][4][0.5]

Unroll

unroll unfolds sequences stored in data, multiplying other ones when necessary. You can unroll more than one column at once (folded data should have the same size!).

Options:

  • :indexes? if true (or column name), information about index of unrolled sequence is added.
  • :datatypes list of datatypes which should be applied to restored columns, a map

Unroll one column

(api/unroll (api/fold-by DS [:V4]) [:V1])

_unnamed [9 4]:

:V4:V2:V3:V1
B[2 5 8][1.0 1.0 1.0]2
B[2 5 8][1.0 1.0 1.0]1
B[2 5 8][1.0 1.0 1.0]2
C[3 6 9][1.5 1.5 1.5]1
C[3 6 9][1.5 1.5 1.5]2
C[3 6 9][1.5 1.5 1.5]1
A[1 4 7][0.5 0.5 0.5]1
A[1 4 7][0.5 0.5 0.5]2
A[1 4 7][0.5 0.5 0.5]1

Unroll all folded columns

(api/unroll (api/fold-by DS [:V4]) [:V1 :V2 :V3])

_unnamed [9 4]:

:V4:V1:V2:V3
B221.000
B151.000
B281.000
C131.500
C261.500
C191.500
A110.5000
A240.5000
A170.5000

Unroll one by one leads to cartesian product

(-> DS
    (api/fold-by [:V4 :V1])
    (api/unroll [:V2])
    (api/unroll [:V3]))

_unnamed [15 4]:

:V4:V1:V2:V3
C261.500
A110.5000
A110.5000
A170.5000
A170.5000
B151.000
C131.500
C131.500
C191.500
C191.500
A240.5000
B221.000
B221.000
B281.000
B281.000

You can add indexes

(api/unroll (api/fold-by DS [:V1]) [:V4 :V2 :V3] {:indexes? true})

_unnamed [9 5]:

:V1:indexes:V2:V3:V4
1010.5000A
1131.500C
1251.000B
1370.5000A
1491.500C
2021.000B
2140.5000A
2261.500C
2381.000B
(api/unroll (api/fold-by DS [:V1]) [:V4 :V2 :V3] {:indexes? "vector idx"})

_unnamed [9 5]:

:V1vector idx:V2:V3:V4
1010.5000A
1131.500C
1251.000B
1370.5000A
1491.500C
2021.000B
2140.5000A
2261.500C
2381.000B

You can also force datatypes

(-> DS
    (api/fold-by [:V1])
    (api/unroll [:V4 :V2 :V3] {:datatypes {:V4 :string
                                           :V2 :int16
                                           :V3 :float32}})
    (api/info :columns))

_unnamed :column info [4 4]:

:name:size:datatype:categorical?
:V19:object
:V29:int16
:V39:float32
:V49:stringtrue

This works also on grouped dataset

(-> DS
    (api/group-by :V1)
    (api/fold-by [:V1 :V4])
    (api/unroll :V3 {:indexes? true})
    (api/ungroup))

_unnamed [9 5]:

:V4:V1:V2:indexes:V3
A1[1 7]00.5000
A1[1 7]10.5000
B1[5]01.000
C1[3 9]01.500
C1[3 9]11.500
C2[6]01.500
A2[4]00.5000
B2[2 8]01.000
B2[2 8]11.000

Reshape

Reshaping data provides two types of operations:

  • pivot->longer - converting columns to rows
  • pivot->wider - converting rows to columns

Both functions are inspired on tidyr R package and provide almost the same functionality.

All examples are taken from mentioned above documentation.

Both functions work only on regular dataset.

Longer

pivot->longer converts columns to rows. Column names are treated as data.

Arguments:

  • dataset
  • columns selector
  • options:
    • :target-columns - names of the columns created or columns pattern (see below) (default: :$column)
    • :value-column-name - name of the column for values (default: :$value)
    • :splitter - regular expression or function which splits source column names into data
    • :drop-missing? - remove rows with missing? (default: :true)
    • :datatypes - map of target columns data types

:target-columns - can be:

  • column name - source columns names are put there as a data
  • column names as seqence - source columns names after split are put separately into :target-columns as data
  • pattern - is a sequence of names, where some of the names are nil. nil is replaced by a name taken from splitter and such column is used for values.

Create rows from all columns but "religion".

(def relig-income (api/dataset "data/relig_income.csv"))
relig-income

data/relig_income.csv [18 11]:

religion<$10k$10-20k$20-30k$30-40k$40-50k$50-75k$75-100k$100-150k>150kDon't know/refused
Agnostic27346081761371221098496
Atheist12273752357073597476
Buddhist27213034335862395354
Catholic41861773267063811169497926331489
Don’t know/refused151415111035211718116
Evangelical Prot575869106498288114869497234141529
Hindu1979113447485437
Historically Black Prot2282442362381972231318178339
Jehovah's Witness2027242421301511637
Jewish1919252530956987151162
Mainline Prot28949561965565111079397536341328
Mormon294048515611285494269
Muslim67910923168622
Orthodox13172332324738424673
Other Christian971113131418141218
Other Faiths20334046496346404171
Other World Religions5234273448
Unaffiliated217299374365341528407321258597
(api/pivot->longer relig-income (complement #{"religion"}))

data/relig_income.csv [180 3]:

religion:$column:$value
Agnostic<$10k27
Atheist<$10k12
Buddhist<$10k27
Catholic<$10k418
Don’t know/refused<$10k15
Evangelical Prot<$10k575
Hindu<$10k1
Historically Black Prot<$10k228
Jehovah's Witness<$10k20
Jewish<$10k19
Mainline Prot<$10k289
Mormon<$10k29
Muslim<$10k6
Orthodox<$10k13
Other Christian<$10k9
Other Faiths<$10k20
Other World Religions<$10k5
Unaffiliated<$10k217
AgnosticDon't know/refused96
AtheistDon't know/refused76
BuddhistDon't know/refused54
CatholicDon't know/refused1489
Don’t know/refusedDon't know/refused116
Evangelical ProtDon't know/refused1529
HinduDon't know/refused37

Convert only columns starting with "wk" and pack them into :week column, values go to :rank column

(def bilboard (-> (api/dataset "data/billboard.csv.gz")
                  (api/drop-columns #(= :boolean %) :datatype))) ;; drop some boolean columns, tidyr just skips them
(->> bilboard
     (api/column-names)
     (take 13)
     (api/select-columns bilboard))

data/billboard.csv.gz [317 13]:

artisttrackdate.enteredwk1wk2wk3wk4wk5wk6wk7wk8wk9wk10
2 PacBaby Don't Cry (Keep...2000-02-2687827277879499
2Ge+herThe Hardest Part Of ...2000-09-02918792
3 Doors DownKryptonite2000-04-0881706867665754535151
3 Doors DownLoser2000-10-2176767269676555596261
504 BoyzWobble Wobble2000-04-1557342517173136495357
98^0Give Me Just One Nig...2000-08-195139342626192236
A*TeensDancing Queen2000-07-0897979695100
AaliyahI Don't Wanna2000-01-2984625141383535383836
AaliyahTry Again2000-03-1859533828211816141210
Adams, YolandaOpen My Heart2000-08-2676767469686761585759
Adkins, TraceMore2000-04-2984847573736968657383
Aguilera, ChristinaCome On Over Baby (A...2000-08-05574745292318119911
Aguilera, ChristinaI Turn To You2000-04-1550393028211920171717
Aguilera, ChristinaWhat A Girl Wants1999-11-2771512818131311112
Alice DeejayBetter Off Alone2000-04-0879655348453634292730
Allan, GarySmoke Rings In The D...2000-01-228078767792
AmberSexual1999-07-1799999696100939396
AnastaciaI'm Outta Love2000-04-0192 95
Anthony, MarcMy Baby You2000-09-1682767670828174807676
Anthony, MarcYou Sang To Me2000-02-2677545043302721181513
AvantMy First Love2000-11-0470625643393326262631
AvantSeparated2000-04-2962323023263035323225
BBMakBack Here2000-04-2999866052383428211818
Backstreet Boys, TheShape Of My Heart2000-10-143925241512121091012
Backstreet Boys, TheShow Me The Meaning ...2000-01-017462552516141210129
(api/pivot->longer bilboard #(clojure.string/starts-with? % "wk") {:target-columns :week
                                                                   :value-column-name :rank})

data/billboard.csv.gz [5307 5]:

artisttrackdate.entered:week:rank
3 Doors DownKryptonite2000-04-08wk354
Braxton, ToniHe Wasn't Man Enough2000-03-18wk3534
CreedHigher1999-09-11wk3522
CreedWith Arms Wide Open2000-05-13wk355
Hill, FaithBreathe1999-11-06wk358
JoeI Wanna Know2000-01-01wk355
LonestarAmazed1999-06-05wk3514
Vertical HorizonEverything You Want2000-01-22wk3527
matchbox twentyBent2000-04-29wk3533
CreedHigher1999-09-11wk5521
LonestarAmazed1999-06-05wk5522
3 Doors DownKryptonite2000-04-08wk1918
3 Doors DownLoser2000-10-21wk1973
98^0Give Me Just One Nig...2000-08-19wk1993
AaliyahI Don't Wanna2000-01-29wk1983
AaliyahTry Again2000-03-18wk193
Adams, YolandaOpen My Heart2000-08-26wk1979
Aguilera, ChristinaCome On Over Baby (A...2000-08-05wk1923
Aguilera, ChristinaI Turn To You2000-04-15wk1929
Aguilera, ChristinaWhat A Girl Wants1999-11-27wk1918
Alice DeejayBetter Off Alone2000-04-08wk1979
AmberSexual1999-07-17wk1995
Anthony, MarcMy Baby You2000-09-16wk1991
Anthony, MarcYou Sang To Me2000-02-26wk199
AvantMy First Love2000-11-04wk1981

We can create numerical column out of column names

(api/pivot->longer bilboard #(clojure.string/starts-with? % "wk") {:target-columns :week
                                                                   :value-column-name :rank
                                                                   :splitter #"wk(.*)"
                                                                   :datatypes {:week :int16}})

data/billboard.csv.gz [5307 5]:

artisttrackdate.entered:week:rank
3 Doors DownKryptonite2000-04-084621
CreedHigher1999-09-11467
CreedWith Arms Wide Open2000-05-134637
Hill, FaithBreathe1999-11-064631
LonestarAmazed1999-06-05465
3 Doors DownKryptonite2000-04-085142
CreedHigher1999-09-115114
Hill, FaithBreathe1999-11-065149
LonestarAmazed1999-06-055112
2 PacBaby Don't Cry (Keep...2000-02-26694
3 Doors DownKryptonite2000-04-08657
3 Doors DownLoser2000-10-21665
504 BoyzWobble Wobble2000-04-15631
98^0Give Me Just One Nig...2000-08-19619
AaliyahI Don't Wanna2000-01-29635
AaliyahTry Again2000-03-18618
Adams, YolandaOpen My Heart2000-08-26667
Adkins, TraceMore2000-04-29669
Aguilera, ChristinaCome On Over Baby (A...2000-08-05618
Aguilera, ChristinaI Turn To You2000-04-15619
Aguilera, ChristinaWhat A Girl Wants1999-11-27613
Alice DeejayBetter Off Alone2000-04-08636
AmberSexual1999-07-17693
Anthony, MarcMy Baby You2000-09-16681
Anthony, MarcYou Sang To Me2000-02-26627

When column names contain observation data, such column names can be splitted and data can be restored into separate columns.

(def who (api/dataset "data/who.csv.gz"))
(->> who
     (api/column-names)
     (take 10)
     (api/select-columns who))

data/who.csv.gz [7240 10]:

countryiso2iso3yearnew_sp_m014new_sp_m1524new_sp_m2534new_sp_m3544new_sp_m4554new_sp_m5564
AfghanistanAFAFG1980
AfghanistanAFAFG1981
AfghanistanAFAFG1982
AfghanistanAFAFG1983
AfghanistanAFAFG1984
AfghanistanAFAFG1985
AfghanistanAFAFG1986
AfghanistanAFAFG1987
AfghanistanAFAFG1988
AfghanistanAFAFG1989
AfghanistanAFAFG1990
AfghanistanAFAFG1991
AfghanistanAFAFG1992
AfghanistanAFAFG1993
AfghanistanAFAFG1994
AfghanistanAFAFG1995
AfghanistanAFAFG1996
AfghanistanAFAFG19970106352
AfghanistanAFAFG199830129128908964
AfghanistanAFAFG199985555473421
AfghanistanAFAFG20005222818314912994
AfghanistanAFAFG2001129379349274204139
AfghanistanAFAFG200290476481368246241
AfghanistanAFAFG2003127511436284256288
AfghanistanAFAFG2004139537568360358386
(api/pivot->longer who #(clojure.string/starts-with? % "new") {:target-columns [:diagnosis :gender :age]
                                                               :splitter #"new_?(.*)_(.)(.*)"
                                                               :value-column-name :count})

data/who.csv.gz [76046 8]:

countryiso2iso3year:diagnosis:gender:age:count
AlbaniaALALB2013relm152460
AlgeriaDZDZA2013relm15241021
AndorraADAND2013relm15240
AngolaAOAGO2013relm15242992
AnguillaAIAIA2013relm15240
Antigua and BarbudaAGATG2013relm15241
ArgentinaARARG2013relm15241124
ArmeniaAMARM2013relm1524116
AustraliaAUAUS2013relm1524105
AustriaATAUT2013relm152444
AzerbaijanAZAZE2013relm1524958
BahamasBSBHS2013relm15242
BahrainBHBHR2013relm152413
BangladeshBDBGD2013relm152414705
BarbadosBBBRB2013relm15240
BelarusBYBLR2013relm1524162
BelgiumBEBEL2013relm152463
BelizeBZBLZ2013relm15248
BeninBJBEN2013relm1524301
BermudaBMBMU2013relm15240
BhutanBTBTN2013relm1524180
Bolivia (Plurinational State of)BOBOL2013relm15241470
Bonaire, Saint Eustatius and SabaBQBES2013relm15240
Bosnia and HerzegovinaBABIH2013relm152457
BotswanaBWBWA2013relm1524423

When data contains multiple observations per row, we can use splitter and pattern for target columns to create new columns and put values there. In following dataset we have two obseravations dob and gender for two childs. We want to put child infomation into the column and leave dob and gender for values.

(def family (api/dataset "data/family.csv"))
family

data/family.csv [5 5]:

familydob_child1dob_child2gender_child1gender_child2
11998-11-262000-01-2912
21996-06-22 2
32002-07-112004-04-0522
42004-10-102009-08-2711
52000-12-052005-02-2821
(api/pivot->longer family (complement #{"family"}) {:target-columns [nil :child]
                                                    :splitter #(clojure.string/split % #"_")
                                                    :datatypes {"gender" :int16}})

data/family.csv [9 4]:

family:childdobgender
1child11998-11-261
2child11996-06-222
3child12002-07-112
4child12004-10-101
5child12000-12-052
1child22000-01-292
3child22004-04-052
4child22009-08-271
5child22005-02-281

Similar here, we have two observations: x and y in four groups.

(def anscombe (api/dataset "data/anscombe.csv"))
anscombe

data/anscombe.csv [11 8]:

x1x2x3x4y1y2y3y4
10101088.0409.1407.4606.580
88886.9508.1406.7705.760
13131387.5808.74012.747.710
99988.8108.7707.1108.840
11111188.3309.2607.8108.470
14141489.9608.1008.8407.040
66687.2406.1306.0805.250
444194.2603.1005.39012.50
121212810.849.1308.1505.560
77784.8207.2606.4207.910
55585.6804.7405.7306.890
(api/pivot->longer anscombe :all {:splitter #"(.)(.)"
                                  :target-columns [nil :set]})

data/anscombe.csv [44 3]:

:setxy
1108.040
186.950
1137.580
198.810
1118.330
1149.960
167.240
144.260
11210.84
174.820
155.680
2109.140
288.140
2138.740
298.770
2119.260
2148.100
266.130
243.100
2129.130
277.260
254.740
3107.460
386.770
31312.74

(def pnl (api/dataset {:x [1 2 3 4]
                       :a [1 1 0 0]
                       :b [0 1 1 1]
                       :y1 (repeatedly 4 rand)
                       :y2 (repeatedly 4 rand)
                       :z1 [3 3 3 3]
                       :z2 [-2 -2 -2 -2]}))
pnl

_unnamed [4 7]:

:x:a:b:y1:y2:z1:z2
1100.60750.94453-2
2110.89920.40183-2
3010.70100.87783-2
4010.048820.79933-2
(api/pivot->longer pnl [:y1 :y2 :z1 :z2] {:target-columns [nil :times]
                                          :splitter #":(.)(.)"})

_unnamed [8 6]:

:x:a:b:timesyz
11010.60753
21110.89923
30110.70103
40110.048823
11020.9445-2
21120.4018-2
30120.8778-2
40120.7993-2

Wider

pivot->wider converts rows to columns.

Arguments:

  • dataset
  • columns-selector - values from selected columns are converted to new columns
  • value-columns - what are values

When multiple columns are used as columns selector, names are joined using :concat-columns-with option. :concat-columns-with can be a string or function (default: "_"). Function accepts sequence of names.

When columns-selector creates non unique set of values, they are folded using :fold-fn (default: vec) option.

When value-columns is a sequence, multiple observations as columns are created appending value column names into new columns. Column names are joined using :concat-value-with option. :concat-value-with can be a string or function (default: "-"). Function accepts current column name and value.


Use station as a name source for columns and seen for values

(def fish (api/dataset "data/fish_encounters.csv"))
fish

data/fish_encounters.csv [114 3]:

fishstationseen
4842Release1
4842I80_11
4842Lisbon1
4842Rstr1
4842Base_TD1
4842BCE1
4842BCW1
4842BCE21
4842BCW21
4842MAE1
4842MAW1
4843Release1
4843I80_11
4843Lisbon1
4843Rstr1
4843Base_TD1
4843BCE1
4843BCW1
4843BCE21
4843BCW21
4843MAE1
4843MAW1
4844Release1
4844I80_11
4844Lisbon1
(api/pivot->wider fish "station" "seen")

data/fish_encounters.csv [19 12]:

fishRstrBase_TDI80_1ReleaseMAEBCE2MAWBCW2BCELisbonBCW
484211111111111
484311111111111
484411111111111
48501111 1 1
48571111 1 1111
485811111111111
486111111111111
48621111 1 1111
4864 11
4865 11 1
48451111 1
4847 11 1
48481 11 1
4849 11
4851 11
4854 11
48551111 1
48591111 1
4863 11

If selected columns contain multiple values, such values should be folded.

(def warpbreaks (api/dataset "data/warpbreaks.csv"))
warpbreaks

data/warpbreaks.csv [54 3]:

breakswooltension
26AL
30AL
54AL
25AL
70AL
52AL
51AL
26AL
67AL
18AM
21AM
29AM
17AM
12AM
18AM
35AM
30AM
36AM
36AH
21AH
24AH
18AH
10AH
43AH
28AH

Let's see how many values are for each type of wool and tension groups

(-> warpbreaks
    (api/group-by ["wool" "tension"])
    (api/aggregate {:n api/row-count}))

_unnamed [6 3]:

wooltension:n
AH9
BH9
AL9
AM9
BL9
BM9
(-> warpbreaks
    (api/reorder-columns ["wool" "tension" "breaks"])
    (api/pivot->wider "wool" "breaks" {:fold-fn vec}))

data/warpbreaks.csv [3 3]:

tensionBA
M[42 26 19 16 39 28 21 39 29][18 21 29 17 12 18 35 30 36]
H[20 21 24 17 13 15 15 16 28][36 21 24 18 10 43 28 15 26]
L[27 14 29 19 29 31 41 20 44][26 30 54 25 70 52 51 26 67]

We can also calculate mean (aggreate values)

(-> warpbreaks
    (api/reorder-columns ["wool" "tension" "breaks"])
    (api/pivot->wider "wool" "breaks" {:fold-fn tech.v2.datatype.functional/mean}))

data/warpbreaks.csv [3 3]:

tensionBA
H18.7824.56
M28.7824.00
L28.2244.56

Multiple source columns, joined with default separator.

(def production (api/dataset "data/production.csv"))
production

data/production.csv [45 4]:

productcountryyearproduction
AAI20001.637
AAI20010.1587
AAI2002-1.568
AAI2003-0.4446
AAI2004-0.07134
AAI20051.612
AAI2006-0.7043
AAI2007-1.536
AAI20080.8391
AAI2009-0.3742
AAI2010-0.7116
AAI20111.128
AAI20121.457
AAI2013-1.559
AAI2014-0.1170
BAI2000-0.02618
BAI2001-0.6886
BAI20020.06249
BAI2003-0.7234
BAI20040.4725
BAI2005-0.9417
BAI2006-0.3478
BAI20070.5243
BAI20081.832
BAI20090.1071
(api/pivot->wider production ["product" "country"] "production")

data/production.csv [15 4]:

yearA_AIB_EIB_AI
20001.6371.405-0.02618
20010.1587-0.5962-0.6886
2002-1.568-0.26570.06249
2003-0.44460.6526-0.7234
2004-0.071340.62560.4725
20051.612-1.345-0.9417
2006-0.7043-0.9718-0.3478
2007-1.536-1.6970.5243
20080.83910.045561.832
2009-0.37421.1930.1071
2010-0.7116-1.606-0.3290
20111.128-0.7724-1.783
20121.457-2.5030.6113
2013-1.559-1.628-0.7853
2014-0.11700.033300.9784

Joined with custom function

(api/pivot->wider production ["product" "country"] "production" {:concat-columns-with vec})

data/production.csv [15 4]:

year["A" "AI"]["B" "EI"]["B" "AI"]
20001.6371.405-0.02618
20010.1587-0.5962-0.6886
2002-1.568-0.26570.06249
2003-0.44460.6526-0.7234
2004-0.071340.62560.4725
20051.612-1.345-0.9417
2006-0.7043-0.9718-0.3478
2007-1.536-1.6970.5243
20080.83910.045561.832
2009-0.37421.1930.1071
2010-0.7116-1.606-0.3290
20111.128-0.7724-1.783
20121.457-2.5030.6113
2013-1.559-1.628-0.7853
2014-0.11700.033300.9784

Multiple value columns

(def income (api/dataset "data/us_rent_income.csv"))
income

data/us_rent_income.csv [104 5]:

GEOIDNAMEvariableestimatemoe
1Alabamaincome24476136
1Alabamarent7473
2Alaskaincome32940508
2Alaskarent120013
4Arizonaincome27517148
4Arizonarent9724
5Arkansasincome23789165
5Arkansasrent7095
6Californiaincome29454109
6Californiarent13583
8Coloradoincome32401109
8Coloradorent11255
9Connecticutincome35326195
9Connecticutrent11235
10Delawareincome31560247
10Delawarerent107610
11District of Columbiaincome43198681
11District of Columbiarent142417
12Floridaincome2595270
12Floridarent10773
13Georgiaincome27024106
13Georgiarent9273
15Hawaiiincome32453218
15Hawaiirent150718
16Idahoincome25298208
(api/pivot->wider income "variable" ["estimate" "moe"])

data/us_rent_income.csv [52 6]:

GEOIDNAMEestimate-rentmoe-rentestimate-incomemoe-income
1Alabama747324476136
2Alaska12001332940508
4Arizona972427517148
5Arkansas709523789165
6California1358329454109
8Colorado1125532401109
9Connecticut1123535326195
10Delaware10761031560247
11District of Columbia14241743198681
12Florida107732595270
13Georgia927327024106
15Hawaii15071832453218
16Idaho792725298208
17Illinois95233068483
18Indiana782327247117
19Iowa740430002143
20Kansas801529126208
21Kentucky713424702159
22Louisiana825425086155
23Maine808726841187
24Maryland1311537147152
25Massachusetts1173534498199
26Michigan82432698782
27Minnesota906432734189
28Mississippi740522766194

Value concatenated by custom function

(api/pivot->wider income "variable" ["estimate" "moe"] {:concat-columns-with vec
                                                        :concat-value-with vector})

data/us_rent_income.csv [52 6]:

GEOIDNAME["rent" "estimate"]["rent" "moe"]["income" "estimate"]["income" "moe"]
1Alabama747324476136
2Alaska12001332940508
4Arizona972427517148
5Arkansas709523789165
6California1358329454109
8Colorado1125532401109
9Connecticut1123535326195
10Delaware10761031560247
11District of Columbia14241743198681
12Florida107732595270
13Georgia927327024106
15Hawaii15071832453218
16Idaho792725298208
17Illinois95233068483
18Indiana782327247117
19Iowa740430002143
20Kansas801529126208
21Kentucky713424702159
22Louisiana825425086155
23Maine808726841187
24Maryland1311537147152
25Massachusetts1173534498199
26Michigan82432698782
27Minnesota906432734189
28Mississippi740522766194

Reshape contact data

(def contacts (api/dataset "data/contacts.csv"))
contacts

data/contacts.csv [6 3]:

fieldvalueperson_id
nameJiena McLellan1
companyToyota1
nameJohn Smith2
companygoogle2
emailjohn@google.com2
nameHuxley Ratcliffe3
(api/pivot->wider contacts "field" "value")

data/contacts.csv [3 4]:

person_idemailnamecompany
1 Jiena McLellanToyota
2john@google.comJohn Smithgoogle
3 Huxley Ratcliffe

Reshaping

A couple of tidyr examples of more complex reshaping.


World bank

(def world-bank-pop (api/dataset "data/world_bank_pop.csv.gz"))
(->> world-bank-pop
     (api/column-names)
     (take 8)
     (api/select-columns world-bank-pop))

data/world_bank_pop.csv.gz [1056 8]:

countryindicator200020012002200320042005
ABWSP.URB.TOTL4.244E+044.305E+044.367E+044.425E+044.467E+044.489E+04
ABWSP.URB.GROW1.1831.4131.4351.3100.95150.4913
ABWSP.POP.TOTL9.085E+049.290E+049.499E+049.702E+049.874E+041.000E+05
ABWSP.POP.GROW2.0552.2262.2292.1091.7571.302
AFGSP.URB.TOTL4.436E+064.648E+064.893E+065.156E+065.427E+065.692E+06
AFGSP.URB.GROW3.9124.6635.1355.2305.1244.769
AFGSP.POP.TOTL2.009E+072.097E+072.198E+072.306E+072.412E+072.507E+07
AFGSP.POP.GROW3.4954.2524.7214.8184.4693.870
AGOSP.URB.TOTL8.235E+068.708E+069.219E+069.765E+061.034E+071.095E+07
AGOSP.URB.GROW5.4375.5885.7005.7585.7535.693
AGOSP.POP.TOTL1.644E+071.698E+071.757E+071.820E+071.887E+071.955E+07
AGOSP.POP.GROW3.0333.2453.4123.5263.5743.576
ALBSP.URB.TOTL1.289E+061.299E+061.327E+061.355E+061.382E+061.407E+06
ALBSP.URB.GROW0.74250.71042.1812.0601.9721.826
ALBSP.POP.TOTL3.089E+063.060E+063.051E+063.040E+063.027E+063.011E+06
ALBSP.POP.GROW-0.6374-0.9385-0.2999-0.3741-0.4179-0.5118
ANDSP.URB.TOTL6.042E+046.199E+046.419E+046.675E+046.919E+047.121E+04
ANDSP.URB.GROW1.2792.5723.4923.9003.5982.868
ANDSP.POP.TOTL6.539E+046.734E+047.005E+047.318E+047.624E+047.887E+04
ANDSP.POP.GROW1.5722.9403.9434.3754.0993.382
ARBSP.URB.TOTL1.500E+081.539E+081.580E+081.623E+081.668E+081.718E+08
ARBSP.URB.GROW2.6002.6292.6392.7102.8062.993
ARBSP.POP.TOTL2.838E+082.899E+082.960E+083.024E+083.092E+083.163E+08
ARBSP.POP.GROW2.1112.1202.1312.1652.2242.297
ARESP.URB.TOTL2.531E+062.683E+062.843E+063.049E+063.347E+063.767E+06

Step 1 - convert years column into values

(def pop2 (api/pivot->longer world-bank-pop (map str (range 2000 2018)) {:drop-missing? false
                                                                         :target-columns ["year"]
                                                                         :value-column-name "value"}))
pop2

data/world_bank_pop.csv.gz [19008 4]:

countryindicatoryearvalue
ABWSP.URB.TOTL20134.436E+04
ABWSP.URB.GROW20130.6695
ABWSP.POP.TOTL20131.032E+05
ABWSP.POP.GROW20130.5929
AFGSP.URB.TOTL20137.734E+06
AFGSP.URB.GROW20134.193
AFGSP.POP.TOTL20133.173E+07
AFGSP.POP.GROW20133.315
AGOSP.URB.TOTL20131.612E+07
AGOSP.URB.GROW20134.723
AGOSP.POP.TOTL20132.600E+07
AGOSP.POP.GROW20133.532
ALBSP.URB.TOTL20131.604E+06
ALBSP.URB.GROW20131.744
ALBSP.POP.TOTL20132.895E+06
ALBSP.POP.GROW2013-0.1832
ANDSP.URB.TOTL20137.153E+04
ANDSP.URB.GROW2013-2.119
ANDSP.POP.TOTL20138.079E+04
ANDSP.POP.GROW2013-2.013
ARBSP.URB.TOTL20132.186E+08
ARBSP.URB.GROW20132.783
ARBSP.POP.TOTL20133.817E+08
ARBSP.POP.GROW20132.249
ARESP.URB.TOTL20137.661E+06

Step 2 - separate "indicate" column

(def pop3 (api/separate-column pop2
                               "indicator" ["area" "variable"]
                               #(rest (clojure.string/split % #"\."))))
pop3

data/world_bank_pop.csv.gz [19008 5]:

countryareavariableyearvalue
ABWURBTOTL20134.436E+04
ABWURBGROW20130.6695
ABWPOPTOTL20131.032E+05
ABWPOPGROW20130.5929
AFGURBTOTL20137.734E+06
AFGURBGROW20134.193
AFGPOPTOTL20133.173E+07
AFGPOPGROW20133.315
AGOURBTOTL20131.612E+07
AGOURBGROW20134.723
AGOPOPTOTL20132.600E+07
AGOPOPGROW20133.532
ALBURBTOTL20131.604E+06
ALBURBGROW20131.744
ALBPOPTOTL20132.895E+06
ALBPOPGROW2013-0.1832
ANDURBTOTL20137.153E+04
ANDURBGROW2013-2.119
ANDPOPTOTL20138.079E+04
ANDPOPGROW2013-2.013
ARBURBTOTL20132.186E+08
ARBURBGROW20132.783
ARBPOPTOTL20133.817E+08
ARBPOPGROW20132.249
AREURBTOTL20137.661E+06

Step 3 - Make columns based on "variable" values.

(api/pivot->wider pop3 "variable" "value")

data/world_bank_pop.csv.gz [9504 5]:

countryareayearGROWTOTL
ABWURB20130.66954.436E+04
ABWPOP20130.59291.032E+05
AFGURB20134.1937.734E+06
AFGPOP20133.3153.173E+07
AGOURB20134.7231.612E+07
AGOPOP20133.5322.600E+07
ALBURB20131.7441.604E+06
ALBPOP2013-0.18322.895E+06
ANDURB2013-2.1197.153E+04
ANDPOP2013-2.0138.079E+04
ARBURB20132.7832.186E+08
ARBPOP20132.2493.817E+08
AREURB20131.5557.661E+06
AREPOP20131.1829.006E+06
ARGURB20131.1883.882E+07
ARGPOP20131.0474.254E+07
ARMURB20130.28101.828E+06
ARMPOP20130.40132.894E+06
ASMURB20130.057984.831E+04
ASMPOP20130.13935.531E+04
ATGURB20130.38382.480E+04
ATGPOP20131.0769.782E+04
AUSURB20131.8751.979E+07
AUSPOP20131.7582.315E+07
AUTURB20130.91964.862E+06


Multi-choice

(def multi (api/dataset {:id [1 2 3 4]
                         :choice1 ["A" "C" "D" "B"]
                         :choice2 ["B" "B" nil "D"]
                         :choice3 ["C" nil nil nil]}))
multi

_unnamed [4 4]:

:id:choice1:choice2:choice3
1ABC
2CB
3D
4BD

Step 1 - convert all choices into rows and add artificial column to all values which are not missing.

(def multi2 (-> multi
                (api/pivot->longer (complement #{:id}))
                (api/add-or-replace-column :checked true)))
multi2

_unnamed [8 4]:

:id:$column:$value:checked
1:choice1Atrue
2:choice1Ctrue
3:choice1Dtrue
4:choice1Btrue
1:choice2Btrue
2:choice2Btrue
4:choice2Dtrue
1:choice3Ctrue

Step 2 - Convert back to wide form with actual choices as columns

(-> multi2
    (api/drop-columns :$column)
    (api/pivot->wider :$value :checked {:drop-missing? false})
    (api/order-by :id))

_unnamed [4 5]:

:idABCD
1truetruetrue
2 truetrue
3 true
4 true true


Construction

(def construction (api/dataset "data/construction.csv"))
(def construction-unit-map {"1 unit" "1"
                            "2 to 4 units" "2-4"
                            "5 units or more" "5+"})
construction

data/construction.csv [9 9]:

YearMonth1 unit2 to 4 units5 units or moreNortheastMidwestSouthWest
2018January859 348114169596339
2018February882 400138160655336
2018March862 356150154595330
2018April797 447144196613304
2018May875 36490169673319
2018June867 34276170610360
2018July829 360108183594310
2018August939 28690205649286
2018September835 304117175560296

Conversion 1 - Group two column types

(-> construction
    (api/pivot->longer #"^[125NWS].*|Midwest" {:target-columns [:units :region]
                                               :splitter (fn [col-name]
                                                           (if (re-matches #"^[125].*" col-name)
                                                             [(construction-unit-map col-name) nil]
                                                             [nil col-name]))
                                               :value-column-name :n
                                               :drop-missing? false}))

data/construction.csv [63 5]:

YearMonth:units:region:n
2018January1 859
2018February1 882
2018March1 862
2018April1 797
2018May1 875
2018June1 867
2018July1 829
2018August1 939
2018September1 835
2018January2-4
2018February2-4
2018March2-4
2018April2-4
2018May2-4
2018June2-4
2018July2-4
2018August2-4
2018September2-4
2018January5+ 348
2018February5+ 400
2018March5+ 356
2018April5+ 447
2018May5+ 364
2018June5+ 342
2018July5+ 360

Conversion 2 - Convert to longer form and back and rename columns

(-> construction
    (api/pivot->longer #"^[125NWS].*|Midwest" {:target-columns [:units :region]
                                               :splitter (fn [col-name]
                                                           (if (re-matches #"^[125].*" col-name)
                                                             [(construction-unit-map col-name) nil]
                                                             [nil col-name]))
                                               :value-column-name :n
                                               :drop-missing? false})
    (api/pivot->wider [:units :region] :n)
    (api/rename-columns (zipmap (vals construction-unit-map)
                                (keys construction-unit-map))))

data/construction.csv [9 9]:

YearMonthMidwest5 units or more2 to 4 unitsNortheastSouth1 unitWest
2018January169348 114596859339
2018February160400 138655882336
2018March154356 150595862330
2018April196447 144613797304
2018May169364 90673875319
2018June170342 76610867360
2018July183360 108594829310
2018August205286 90649939286
2018September175304 117560835296


Various operations on stocks, examples taken from gather and spread manuals.

(def stocks-tidyr (api/dataset "data/stockstidyr.csv"))
stocks-tidyr

data/stockstidyr.csv [10 4]:

timeXYZ
2009-01-011.310-1.890-1.779
2009-01-02-0.2999-1.8252.399
2009-01-030.5365-1.036-3.987
2009-01-04-1.884-0.5218-2.831
2009-01-05-0.9605-2.2171.437
2009-01-06-1.185-2.8943.398
2009-01-07-0.8521-2.168-1.201
2009-01-080.2523-0.3285-1.532
2009-01-090.40261.964-6.809
2009-01-10-0.64382.686-2.559

Convert to longer form

(def stocks-long (api/pivot->longer stocks-tidyr ["X" "Y" "Z"] {:value-column-name :price
                                                                :target-columns :stocks}))
stocks-long

data/stockstidyr.csv [30 3]:

time:stocks:price
2009-01-01X1.310
2009-01-02X-0.2999
2009-01-03X0.5365
2009-01-04X-1.884
2009-01-05X-0.9605
2009-01-06X-1.185
2009-01-07X-0.8521
2009-01-08X0.2523
2009-01-09X0.4026
2009-01-10X-0.6438
2009-01-01Y-1.890
2009-01-02Y-1.825
2009-01-03Y-1.036
2009-01-04Y-0.5218
2009-01-05Y-2.217
2009-01-06Y-2.894
2009-01-07Y-2.168
2009-01-08Y-0.3285
2009-01-09Y1.964
2009-01-10Y2.686
2009-01-01Z-1.779
2009-01-02Z2.399
2009-01-03Z-3.987
2009-01-04Z-2.831
2009-01-05Z1.437

Convert back to wide form

(api/pivot->wider stocks-long :stocks :price)

data/stockstidyr.csv [10 4]:

timeZXY
2009-01-01-1.7791.310-1.890
2009-01-022.399-0.2999-1.825
2009-01-03-3.9870.5365-1.036
2009-01-04-2.831-1.884-0.5218
2009-01-051.437-0.9605-2.217
2009-01-063.398-1.185-2.894
2009-01-07-1.201-0.8521-2.168
2009-01-08-1.5320.2523-0.3285
2009-01-09-6.8090.40261.964
2009-01-10-2.559-0.64382.686

Convert to wide form on time column (let's limit values to a couple of rows)

(-> stocks-long
    (api/select-rows (range 0 30 4))
    (api/pivot->wider "time" :price))

data/stockstidyr.csv [3 6]:

:stocks2009-01-052009-01-072009-01-012009-01-032009-01-09
X-0.9605 1.310 0.4026
Z1.437 -1.779 -6.809
Y -2.168 -1.036

Join/Concat Datasets

Dataset join and concatenation functions.

Joins accept left-side and right-side datasets and columns selector. Options are the same as in tech.ml.dataset functions.

The difference between tech.ml.dataset join functions are: arguments order (first datasets) and possibility to join on multiple columns.

Additionally set operations are defined: intersect and difference.

To concat two datasets rowwise you can choose:

  • concat - concats rows for matching columns, the number of columns should be equal.
  • union - like concat but returns unique values
  • bind - concats rows add missing, empty columns

To add two datasets columnwise use bind. The number of rows should be equal.

Datasets used in examples:

(def ds1 (api/dataset {:a [1 2 1 2 3 4 nil nil 4]
                       :b (range 101 110)
                       :c (map str "abs tract")}))
(def ds2 (api/dataset {:a [nil 1 2 5 4 3 2 1 nil]
                       :b (range 110 101 -1)
                       :c (map str "datatable")
                       :d (symbol "X")}))
ds1
ds2

_unnamed [9 3]:

:a:b:c
1101a
2102b
1103s
2104
3105t
4106r
107a
108c
4109t

_unnamed [9 4]:

:a:b:c:d
110dX
1109aX
2108tX
5107aX
4106tX
3105aX
2104bX
1103lX
102eX

Left

(api/left-join ds1 ds2 :b)

left-outer-join [9 7]:

:b:a:c:right.b:right.a:right.c:d
1094t1091aX
108 c1082tX
107 a1075aX
1064r1064tX
1053t1053aX
1042 1042bX
1031s1031lX
1022b102 eX
1011a

(api/left-join ds2 ds1 :b)

left-outer-join [9 7]:

:b:a:c:d:right.b:right.a:right.c
102 eX1022b
1031lX1031s
1042bX1042
1053aX1053t
1064tX1064r
1075aX107 a
1082tX108 c
1091aX1094t
110 dX

(api/left-join ds1 ds2 [:a :b])

left-outer-join [9 7]:

:a:b:c:right.a:right.b:right.c:d
4106r4106tX
3105t3105aX
2104 2104bX
1103s1103lX
2102b
108c
107a
1101a
4109t

(api/left-join ds2 ds1 [:a :b])

left-outer-join [9 7]:

:a:b:c:d:right.a:right.b:right.c
1103lX1103s
2104bX2104
3105aX3105t
4106tX4106r
2108tX
1109aX
5107aX
110dX
102eX

Right

(api/right-join ds1 ds2 :b)

right-outer-join [9 7]:

:b:a:c:right.b:right.a:right.c:d
1094t1091aX
108 c1082tX
107 a1075aX
1064r1064tX
1053t1053aX
1042 1042bX
1031s1031lX
1022b102 eX
110 dX

(api/right-join ds2 ds1 :b)

right-outer-join [9 7]:

:b:a:c:d:right.b:right.a:right.c
102 eX1022b
1031lX1031s
1042bX1042
1053aX1053t
1064tX1064r
1075aX107 a
1082tX108 c
1091aX1094t
1011a

(api/right-join ds1 ds2 [:a :b])

right-outer-join [9 7]:

:a:b:c:right.a:right.b:right.c:d
4106r4106tX
3105t3105aX
2104 2104bX
1103s1103lX
110dX
1109aX
2108tX
5107aX
102eX

(api/right-join ds2 ds1 [:a :b])

right-outer-join [9 7]:

:a:b:c:d:right.a:right.b:right.c
1103lX1103s
2104bX2104
3105aX3105t
4106tX4106r
1101a
2102b
107a
108c
4109t

Inner

(api/inner-join ds1 ds2 :b)

inner-join [8 6]:

:b:a:c:right.a:right.c:d
1094t1aX
108 c2tX
107 a5aX
1064r4tX
1053t3aX
1042 2bX
1031s1lX
1022b eX

(api/inner-join ds2 ds1 :b)

inner-join [8 6]:

:b:a:c:d:right.a:right.c
102 eX2b
1031lX1s
1042bX2
1053aX3t
1064tX4r
1075aX a
1082tX c
1091aX4t

(api/inner-join ds1 ds2 [:a :b])

inner-join [4 7]:

:a:b:c:right.a:right.b:right.c:d
4106r4106tX
3105t3105aX
2104 2104bX
1103s1103lX

(api/inner-join ds2 ds1 [:a :b])

inner-join [4 7]:

:a:b:c:d:right.a:right.b:right.c
1103lX1103s
2104bX2104
3105aX3105t
4106tX4106r

Full

Join keeping all rows

(api/full-join ds1 ds2 :b)

full-join [10 7]:

:b:a:c:right.b:right.a:right.c:d
1094t1091aX
108 c1082tX
107 a1075aX
1064r1064tX
1053t1053aX
1042 1042bX
1031s1031lX
1022b102 eX
1011a
110 dX

(api/full-join ds2 ds1 :b)

full-join [10 7]:

:b:a:c:d:right.b:right.a:right.c
102 eX1022b
1031lX1031s
1042bX1042
1053aX1053t
1064tX1064r
1075aX107 a
1082tX108 c
1091aX1094t
110 dX
1011a

(api/full-join ds1 ds2 [:a :b])

full-join [14 7]:

:a:b:c:right.a:right.b:right.c:d
4106r4106tX
3105t3105aX
2104 2104bX
1103s1103lX
2102b
108c
107a
1101a
4109t
110dX
1109aX
2108tX
5107aX
102eX

(api/full-join ds2 ds1 [:a :b])

full-join [14 7]:

:a:b:c:d:right.a:right.b:right.c
1103lX1103s
2104bX2104
3105aX3105t
4106tX4106r
2108tX
1109aX
5107aX
110dX
102eX
1101a
2102b
107a
108c
4109t

Semi

Return rows from ds1 matching ds2

(api/semi-join ds1 ds2 :b)

semi-join [5 3]:

:b:a:c
1094t
1064r
1053t
1042
1031s

(api/semi-join ds2 ds1 :b)

semi-join [5 4]:

:b:a:c:d
1031lX
1042bX
1053aX
1064tX
1091aX

(api/semi-join ds1 ds2 [:a :b])

semi-join [4 3]:

:a:b:c
4106r
3105t
2104
1103s

(api/semi-join ds2 ds1 [:a :b])

semi-join [4 4]:

:a:b:c:d
1103lX
2104bX
3105aX
4106tX

Anti

Return rows from ds1 not matching ds2

(api/anti-join ds1 ds2 :b)

anti-join [4 3]:

:b:a:c
108 c
107 a
1022b
1011a

(api/anti-join ds2 ds1 :b)

anti-join [4 4]:

:b:a:c:d
102 eX
1075aX
1082tX
110 dX

(api/anti-join ds1 ds2 [:a :b])

anti-join [5 3]:

:a:b:c
2102b
108c
107a
1101a
4109t

(api/anti-join ds2 ds1 [:a :b])

anti-join [5 4]:

:a:b:c:d
2108tX
1109aX
5107aX
110dX
102eX

Concat

contact joins rows from other datasets

(api/concat ds1)

null [9 3]:

:a:b:c
1101a
2102b
1103s
2104
3105t
4106r
107a
108c
4109t

(api/concat ds1 (api/drop-columns ds2 :d))

null [18 3]:

:a:b:c
1101a
2102b
1103s
2104
3105t
4106r
107a
108c
4109t
110d
1109a
2108t
5107a
4106t
3105a
2104b
1103l
102e

(apply api/concat (repeatedly 3 #(api/random DS)))

null [27 4]:

:V1:V2:V3:V4
131.500C
151.000B
151.000B
281.000B
281.000B
191.500C
110.5000A
170.5000A
240.5000A
221.000B
240.5000A
240.5000A
240.5000A
191.500C
131.500C
151.000B
240.5000A
131.500C
170.5000A
281.000B
131.500C
240.5000A
221.000B
191.500C
261.500C

Union

The same as concat but returns unique rows

(apply api/union (api/drop-columns ds2 :d) (repeat 10 ds1))

union [18 3]:

:a:b:c
110d
1109a
2108t
5107a
4106t
3105a
2104b
1103l
102e
1101a
2102b
1103s
2104
3105t
4106r
107a
108c
4109t

(apply api/union (repeatedly 10 #(api/random DS)))

union [9 4]:

:V1:V2:V3:V4
191.500C
170.5000A
261.500C
131.500C
281.000B
221.000B
240.5000A
151.000B
110.5000A

Bind

bind adds empty columns during concat

(api/bind ds1 ds2)

null [18 4]:

:a:b:c:d
1101a
2102b
1103s
2104
3105t
4106r
107a
108c
4109t
110dX
1109aX
2108tX
5107aX
4106tX
3105aX
2104bX
1103lX
102eX

(api/bind ds2 ds1)

null [18 4]:

:a:b:c:d
110dX
1109aX
2108tX
5107aX
4106tX
3105aX
2104bX
1103lX
102eX
1101a
2102b
1103s
2104
3105t
4106r
107a
108c
4109t

Append

append concats columns

(api/append ds1 ds2)

_unnamed [9 7]:

:a:b:c:a:b:c:d
1101a 110dX
2102b1109aX
1103s2108tX
2104 5107aX
3105t4106tX
4106r3105aX
107a2104bX
108c1103lX
4109t 102eX

Intersection

(api/intersect (api/select-columns ds1 :b)
               (api/select-columns ds2 :b))

intersection [8 1]:

:b
109
108
107
106
105
104
103
102

Difference

(api/difference (api/select-columns ds1 :b)
                (api/select-columns ds2 :b))

difference [1 1]:

:b
101

(api/difference (api/select-columns ds2 :b)
                (api/select-columns ds1 :b))

difference [1 1]:

:b
110

Functions

This API doesn't provide any statistical, numerical or date/time functions. Use below namespaces:

Namespacefunctions
tech.v2.datatype.functionalprimitive oprations, reducers, statistics
tech.v2.datatype.datetimedate/time converters
tech.v2.datatype.datetime.operationsdate/time functions
tech.ml.dataset.pipelinepipeline operations

Other examples

Stocks

(defonce stocks (api/dataset "https://raw.githubusercontent.com/techascent/tech.ml.dataset/master/test/data/stocks.csv" {:key-fn keyword}))
stocks

https://raw.githubusercontent.com/techascent/tech.ml.dataset/master/test/data/stocks.csv [560 3]:

:symbol:date:price
MSFT2000-01-0139.81
MSFT2000-02-0136.35
MSFT2000-03-0143.22
MSFT2000-04-0128.37
MSFT2000-05-0125.45
MSFT2000-06-0132.54
MSFT2000-07-0128.40
MSFT2000-08-0128.40
MSFT2000-09-0124.53
MSFT2000-10-0128.02
MSFT2000-11-0123.34
MSFT2000-12-0117.65
MSFT2001-01-0124.84
MSFT2001-02-0124.00
MSFT2001-03-0122.25
MSFT2001-04-0127.56
MSFT2001-05-0128.14
MSFT2001-06-0129.70
MSFT2001-07-0126.93
MSFT2001-08-0123.21
MSFT2001-09-0120.82
MSFT2001-10-0123.65
MSFT2001-11-0126.12
MSFT2001-12-0126.95
MSFT2002-01-0125.92
(-> stocks
    (api/group-by (fn [row]
                    {:symbol (:symbol row)
                     :year (tech.v2.datatype.datetime.operations/get-years (:date row))}))
    (api/aggregate #(tech.v2.datatype.functional/mean (% :price)))
    (api/order-by [:symbol :year]))

_unnamed [51 3]:

:symbol:year:summary
AAPL200021.75
AAPL200110.18
AAPL20029.408
AAPL20039.347
AAPL200418.72
AAPL200548.17
AAPL200672.04
AAPL2007133.4
AAPL2008138.5
AAPL2009150.4
AAPL2010206.6
AMZN200043.93
AMZN200111.74
AMZN200216.72
AMZN200339.02
AMZN200443.27
AMZN200540.19
AMZN200636.25
AMZN200769.95
AMZN200869.02
AMZN200990.73
AMZN2010124.2
GOOG2004159.5
GOOG2005286.5
GOOG2006415.3
(-> stocks
    (api/group-by (juxt :symbol #(tech.v2.datatype.datetime.operations/get-years (% :date))))
    (api/aggregate #(tech.v2.datatype.functional/mean (% :price)))
    (api/rename-columns {:$group-name-0 :symbol
                         :$group-name-1 :year}))

_unnamed [51 3]:

:symbol:year:summary
AMZN200769.95
AMZN200869.02
AMZN200990.73
AMZN2010124.2
AMZN200043.93
AMZN200111.74
AMZN200216.72
AMZN200339.02
AMZN200443.27
AMZN200540.19
AMZN200636.25
IBM200196.97
IBM200275.13
IBM200096.91
MSFT200624.76
MSFT200523.85
MSFT200422.67
MSFT200320.93
AAPL200110.18
MSFT201028.51
AAPL20029.408
MSFT200922.87
MSFT200825.21
AAPL200021.75
MSFT200729.28

data.table

Below you can find comparizon between functionality of data.table and Clojure dataset API. I leave it without comments, please refer original document explaining details:

Introduction to data.table

R

library(data.table)
library(knitr)

flights <- fread("https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv")

kable(head(flights))
yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
2014111413AAJFKLAX35924759
201411-313AAJFKLAX363247511
20141129AAJFKLAX351247519
201411-8-26AALGAPBI15710357
20141121AAJFKLAX350247513
20141140AAEWRLAX339245418

Clojure

(require '[tech.v2.datatype.functional :as dfn]
         '[tech.v2.datatype :as dtype])

(defonce flights (api/dataset "https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv"))
(api/head flights 6)

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [6 11]:

yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
2014111413AAJFKLAX35924759
201411-313AAJFKLAX363247511
20141129AAJFKLAX351247519
201411-8-26AALGAPBI15710357
20141121AAJFKLAX350247513
20141140AAEWRLAX339245418

Basics

Shape of loaded data

R

dim(flights)
[1] 253316     11

Clojure

(api/shape flights)
[253316 11]
What is data.table?

R

DT = data.table(
  ID = c("b","b","b","a","a","c"),
  a = 1:6,
  b = 7:12,
  c = 13:18
)

kable(DT)
IDabc
b1713
b2814
b3915
a41016
a51117
c61218
class(DT$ID)
[1] "character"

Clojure

(def DT (api/dataset {:ID ["b" "b" "b" "a" "a" "c"]
                      :a (range 1 7)
                      :b (range 7 13)
                      :c (range 13 19)}))
DT

_unnamed [6 4]:

:ID:a:b:c
b1713
b2814
b3915
a41016
a51117
c61218
(-> :ID DT meta :datatype)
:string
Get all the flights with “JFK” as the origin airport in the month of June.

R

ans <- flights[origin == "JFK" & month == 6L]
kable(head(ans))
yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
201461-9-5AAJFKLAX32424758
201461-10-13AAJFKLAX329247512
20146118-1AAJFKLAX32624757
201461-6-16AAJFKLAX320247510
201461-4-45AAJFKLAX326247518
201461-6-23AAJFKLAX329247514

Clojure

(-> flights
    (api/select-rows (fn [row] (and (= (get row "origin") "JFK")
                                   (= (get row "month") 6))))
    (api/head 6))

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [6 11]:

yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
201461-9-5AAJFKLAX32424758
201461-10-13AAJFKLAX329247512
20146118-1AAJFKLAX32624757
201461-6-16AAJFKLAX320247510
201461-4-45AAJFKLAX326247518
201461-6-23AAJFKLAX329247514
Get the first two rows from flights.

R

ans <- flights[1:2]
kable(ans)
yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
2014111413AAJFKLAX35924759
201411-313AAJFKLAX363247511

Clojure

(api/select-rows flights (range 2))

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [2 11]:

yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
2014111413AAJFKLAX35924759
201411-313AAJFKLAX363247511
Sort flights first by column origin in ascending order, and then by dest in descending order

R

ans <- flights[order(origin, -dest)]
kable(head(ans))
yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
201415649EVEWRXNA19511318
201416713EVEWRXNA19011318
201417-6-13EVEWRXNA17911318
201418-7-12EVEWRXNA18411318
201419167EVEWRXNA18111318
20141136666EVEWRXNA18811319

Clojure

(-> flights
    (api/order-by ["origin" "dest"] [:asc :desc])
    (api/head 6))

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [6 11]:

yearmonthdaydep_delayarr_delaycarrierorigindestair_timedistancehour
201463-6-38EVEWRXNA15411316
2014120-9-17EVEWRXNA17711318
2014319-610EVEWRXNA20111316
201423231268EVEWRXNA184113112
2014425-8-32EVEWRXNA15911316
20142192110EVEWRXNA17611318
Select arr_delay column, but return it as a vector

R

ans <- flights[, arr_delay]
head(ans)
[1]  13  13   9 -26   1   0

Clojure

(take 6 (flights "arr_delay"))
(13 13 9 -26 1 0)
Select arr_delay column, but return as a data.table instead

R

ans <- flights[, list(arr_delay)]
kable(head(ans))
arr_delay
13
13
9
-26
1
0

Clojure

(-> flights
    (api/select-columns "arr_delay")
    (api/head 6))

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [6 1]:

arr_delay
13
13
9
-26
1
0
Select both arr_delay and dep_delay columns

R

ans <- flights[, .(arr_delay, dep_delay)]
kable(head(ans))
arr_delaydep_delay
1314
13-3
92
-26-8
12
04

Clojure

(-> flights
    (api/select-columns ["arr_delay" "dep_delay"])
    (api/head 6))

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [6 2]:

dep_delayarr_delay
1413
-313
29
-8-26
21
40
Select both arr_delay and dep_delay columns and rename them to delay_arr and delay_dep

R

ans <- flights[, .(delay_arr = arr_delay, delay_dep = dep_delay)]
kable(head(ans))
delay_arrdelay_dep
1314
13-3
92
-26-8
12
04

Clojure

(-> flights
    (api/select-columns {"arr_delay" "delay_arr"
                         "dep_delay" "delay_arr"})
    (api/head 6))

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [6 2]:

delay_arrdelay_arr
1413
-313
29
-8-26
21
40
How many trips have had total delay < 0?

R

ans <- flights[, sum( (arr_delay + dep_delay) < 0 )]
ans
[1] 141814

Clojure

(->> (dfn/+ (flights "arr_delay") (flights "dep_delay"))
     (dfn/argfilter #(< % 0.0))
     (dtype/ecount))
141814

or pure Clojure functions (much, much slower)

(->> (map + (flights "arr_delay") (flights "dep_delay"))
     (filter neg?)
     (count))
141814
Calculate the average arrival and departure delay for all flights with “JFK” as the origin airport in the month of June

R

ans <- flights[origin == "JFK" & month == 6L,
               .(m_arr = mean(arr_delay), m_dep = mean(dep_delay))]
kable(ans)
m_arrm_dep
5.8393499.807884

Clojure

(-> flights
    (api/select-rows (fn [row] (and (= (get row "origin") "JFK")
                                   (= (get row "month") 6))))
    (api/aggregate {:m_arr #(dfn/mean (% "arr_delay"))
                    :m_dep #(dfn/mean (% "dep_delay"))}))

_unnamed [1 2]:

:m_arr:m_dep
5.8399.808
How many trips have been made in 2014 from “JFK” airport in the month of June?

R

ans <- flights[origin == "JFK" & month == 6L, length(dest)]
ans
[1] 8422

or

ans <- flights[origin == "JFK" & month == 6L, .N]
ans
[1] 8422

Clojure

(-> flights
    (api/select-rows (fn [row] (and (= (get row "origin") "JFK")
                                   (= (get row "month") 6))))
    (api/row-count))
8422
deselect columns using - or !

R

ans <- flights[, !c("arr_delay", "dep_delay")]
kable(head(ans))
yearmonthdaycarrierorigindestair_timedistancehour
201411AAJFKLAX35924759
201411AAJFKLAX363247511
201411AAJFKLAX351247519
201411AALGAPBI15710357
201411AAJFKLAX350247513
201411AAEWRLAX339245418

or

ans <- flights[, -c("arr_delay", "dep_delay")]
kable(head(ans))
yearmonthdaycarrierorigindestair_timedistancehour
201411AAJFKLAX35924759
201411AAJFKLAX363247511
201411AAJFKLAX351247519
201411AALGAPBI15710357
201411AAJFKLAX350247513
201411AAEWRLAX339245418

Clojure

(-> flights
    (api/select-columns (complement #{"arr_delay" "dep_delay"}))
    (api/head 6))

https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv [6 9]:

yearmonthdaycarrierorigindestair_timedistancehour
201411AAJFKLAX35924759
201411AAJFKLAX363247511
201411AAJFKLAX351247519
201411AALGAPBI15710357
201411AAJFKLAX350247513
201411AAEWRLAX339245418

Aggregations

How can we get the number of trips corresponding to each origin airport?

R

ans <- flights[, .(.N), by = .(origin)]
kable(ans)
originN
JFK81483
LGA84433
EWR87400

Clojure

(-> flights
    (api/group-by ["origin"])
    (api/aggregate {:N api/row-count}))

_unnamed [3 2]:

origin:N
LGA84433
EWR87400
JFK81483
How can we calculate the number of trips for each origin airport for carrier code "AA"?

R

ans <- flights[carrier == "AA", .N, by = origin]
kable(ans)
originN
JFK11923
LGA11730
EWR2649

Clojure

(-> flights
    (api/select-rows #(= (get % "carrier") "AA"))
    (api/group-by ["origin"])
    (api/aggregate {:N api/row-count}))

_unnamed [3 2]:

origin:N
LGA11730
EWR2649
JFK11923
How can we get the total number of trips for each origin, dest pair for carrier code "AA"?

R

ans <- flights[carrier == "AA", .N, by = .(origin, dest)]
kable(head(ans))
origindestN
JFKLAX3387
LGAPBI245
EWRLAX62
JFKMIA1876
JFKSEA298
EWRMIA848

Clojure

(-> flights
    (api/select-rows #(= (get % "carrier") "AA"))
    (api/group-by ["origin" "dest"])
    (api/aggregate {:N api/row-count})
    (api/head 6))

_unnamed [6 3]:

origindest:N
JFKMIA1876
LGAPBI245
JFKSEA298
LGADFW3785
JFKAUS297
JFKSTT229
How can we get the average arrival and departure delay for each orig,dest pair for each month for carrier code "AA"?

R

ans <- flights[carrier == "AA",
        .(mean(arr_delay), mean(dep_delay)),
        by = .(origin, dest, month)]
kable(head(ans,10))
origindestmonthV1V2
JFKLAX16.59036114.2289157
LGAPBI1-7.7586210.3103448
EWRLAX11.3666677.5000000
JFKMIA115.72067018.7430168
JFKSEA114.35714330.7500000
EWRMIA111.01123612.1235955
JFKSFO119.25225228.6396396
JFKBOS112.91964315.2142857
JFKORD131.58620740.1724138
JFKIAH128.85714314.2857143

Clojure

(-> flights
    (api/select-rows #(= (get % "carrier") "AA"))
    (api/group-by ["origin" "dest" "month"])
    (api/aggregate [#(dfn/mean (% "arr_delay"))
                    #(dfn/mean (% "dep_delay"))])
    (api/head 10))

_unnamed [10 5]:

monthorigindest:summary-0:summary-1
9LGADFW-8.788-0.2558
10LGADFW3.5004.553
1JFKAUS25.2027.60
4JFKAUS4.367-0.1333
5JFKAUS6.76714.73
2JFKAUS26.2721.50
3JFKAUS8.1942.710
8JFKAUS20.4220.77
1EWRLAX1.3677.500
9JFKAUS16.2714.37
So how can we directly order by all the grouping variables?

R

ans <- flights[carrier == "AA",
        .(mean(arr_delay), mean(dep_delay)),
        keyby = .(origin, dest, month)]
kable(head(ans,10))
origindestmonthV1V2
EWRDFW16.42767310.012579
EWRDFW210.53676511.345588
EWRDFW312.8650318.079755
EWRDFW417.79268312.920732
EWRDFW518.48780518.682927
EWRDFW637.00595238.744048
EWRDFW720.25000021.154762
EWRDFW816.93604622.069767
EWRDFW95.86503113.055215
EWRDFW1018.81366518.894410

Clojure

(-> flights
    (api/select-rows #(= (get % "carrier") "AA"))
    (api/group-by ["origin" "dest" "month"])
    (api/aggregate [#(dfn/mean (% "arr_delay"))
                    #(dfn/mean (% "dep_delay"))])
    (api/order-by ["origin" "dest" "month"])
    (api/head 10))

_unnamed [10 5]:

monthorigindest:summary-0:summary-1
1EWRDFW6.42810.01
2EWRDFW10.5411.35
3EWRDFW12.878.080
4EWRDFW17.7912.92
5EWRDFW18.4918.68
6EWRDFW37.0138.74
7EWRDFW20.2521.15
8EWRDFW16.9422.07
9EWRDFW5.86513.06
10EWRDFW18.8118.89
Can by accept expressions as well or does it just take columns?

R

ans <- flights[, .N, .(dep_delay>0, arr_delay>0)]
kable(ans)
dep_delayarr_delayN
TRUETRUE72836
FALSETRUE34583
FALSEFALSE119304
TRUEFALSE26593

Clojure

(-> flights
    (api/group-by (fn [row]
                    {:dep_delay (pos? (get row "dep_delay"))
                     :arr_delay (pos? (get row "arr_delay"))}))
    (api/aggregate {:N api/row-count}))

_unnamed [4 3]:

:dep_delay:arr_delay:N
truefalse26593
falsetrue34583
falsefalse119304
truetrue72836
Do we have to compute mean() for each column individually?

R

kable(DT)
IDabc
b1713
b2814
b3915
a41016
a51117
c61218
DT[, print(.SD), by = ID]
   a b  c
1: 1 7 13
2: 2 8 14
3: 3 9 15
   a  b  c
1: 4 10 16
2: 5 11 17
   a  b  c
1: 6 12 18

Empty data.table (0 rows and 1 cols): ID
kable(DT[, lapply(.SD, mean), by = ID])
IDabc
b2.08.014.0
a4.510.516.5
c6.012.018.0

Clojure

DT

(api/group-by DT :ID {:result-type :as-map})

_unnamed [6 4]:

:ID:a:b:c
b1713
b2814
b3915
a41016
a51117
c61218

{"a" Group: a [2 4]:

:ID:a:b:c
a41016
a51117

, "b" Group: b [3 4]:

:ID:a:b:c
b1713
b2814
b3915

, "c" Group: c [1 4]:

:ID:a:b:c
c61218

}

(-> DT
    (api/group-by [:ID])
    (api/aggregate-columns (complement #{:ID}) dfn/mean))

_unnamed [3 4]:

:ID:a:b:c
a4.50010.5016.50
b2.0008.00014.00
c6.00012.0018.00
How can we specify just the columns we would like to compute the mean() on?

R

kable(head(flights[carrier == "AA",                         ## Only on trips with carrier "AA"
                   lapply(.SD, mean),                       ## compute the mean
                   by = .(origin, dest, month),             ## for every 'origin,dest,month'
                   .SDcols = c("arr_delay", "dep_delay")])) ## for just those specified in .SDcols
origindestmontharr_delaydep_delay
JFKLAX16.59036114.2289157
LGAPBI1-7.7586210.3103448
EWRLAX11.3666677.5000000
JFKMIA115.72067018.7430168
JFKSEA114.35714330.7500000
EWRMIA111.01123612.1235955

Clojure

(-> flights
    (api/select-rows #(= (get % "carrier") "AA"))
    (api/group-by ["origin" "dest" "month"])
    (api/aggregate-columns ["arr_delay" "dep_delay"] dfn/mean)
    (api/head 6))

_unnamed [6 5]:

monthorigindestdep_delayarr_delay
9LGADFW-0.2558-8.788
10LGADFW4.5533.500
1JFKAUS27.6025.20
4JFKAUS-0.13334.367
5JFKAUS14.736.767
2JFKAUS21.5026.27
How can we return the first two rows for each month?

R

ans <- flights[, head(.SD, 2), by = month]
kable(head(ans))
monthyeardaydep_delayarr_delaycarrierorigindestair_timedistancehour
1201411413AAJFKLAX35924759
120141-313AAJFKLAX363247511
220141-11AAJFKLAX35824758
220141-53AAJFKLAX358247511
320141-1136AAJFKLAX37524758
320141-314AAJFKLAX368247511

Clojure

(-> flights
    (api/group-by ["month"])
    (api/head 2) ;; head applied on each group
    (api/ungroup)
    (api/head 6))

_unnamed [6 11]:

dep_delayoriginair_timehourarr_delaydestdistanceyearmonthdaycarrier
-8LGA11318-23BNA764201441MQ
-8LGA7118-11RDU431201441MQ
43JFK288175LAS2248201451AA
-1JFK3307-38SFO2586201451AA
-9JFK3248-5LAX2475201461AA
-10JFK32912-13LAX2475201461AA
How can we concatenate columns a and b for each group in ID?

R

kable(DT[, .(val = c(a,b)), by = ID])
IDval
b1
b2
b3
b7
b8
b9
a4
a5
a10
a11
c6
c12

Clojure

(-> DT
    (api/pivot->longer [:a :b] {:value-column-name :val})
    (api/drop-columns [:$column :c]))

_unnamed [12 2]:

:ID:val
b1
b2
b3
a4
a5
c6
b7
b8
b9
a10
a11
c12
What if we would like to have all the values of column a and b concatenated, but returned as a list column?

R

kable(DT[, .(val = list(c(a,b))), by = ID])
IDval
bc(1, 2, 3, 7, 8, 9)
ac(4, 5, 10, 11)
cc(6, 12)

Clojure

(-> DT
    (api/pivot->longer [:a :b] {:value-column-name :val})
    (api/drop-columns [:$column :c])
    (api/fold-by :ID))

_unnamed [3 2]:

:ID:val
a[4 5 10 11]
b[1 2 3 7 8 9]
c[6 12]

API tour

Below snippets are taken from A data.table and dplyr tour written by Atrebas (permission granted).

I keep structure and subtitles but I skip data.table and dplyr examples.

Example data

(def DS (api/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"]))}))
(api/dataset? DS)
(class DS)
true
tech.ml.dataset.impl.dataset.Dataset
DS

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Basic Operations

Filter rows

Filter rows using indices

(api/select-rows DS [2 3])

_unnamed [2 4]:

:V1:V2:V3:V4
131.500C
240.5000A

Discard rows using negative indices

In Clojure API we have separate function for that: drop-rows.

(api/drop-rows DS (range 2 7))

_unnamed [4 4]:

:V1:V2:V3:V4
110.5000A
221.000B
281.000B
191.500C

Filter rows using a logical expression

(api/select-rows DS (comp #(> % 5) :V2))

_unnamed [4 4]:

:V1:V2:V3:V4
261.500C
170.5000A
281.000B
191.500C
(api/select-rows DS (comp #{"A" "C"} :V4))

_unnamed [6 4]:

:V1:V2:V3:V4
110.5000A
131.500C
240.5000A
261.500C
170.5000A
191.500C

Filter rows using multiple conditions

(api/select-rows DS #(and (= (:V1 %) 1)
                          (= (:V4 %) "A")))

_unnamed [2 4]:

:V1:V2:V3:V4
110.5000A
170.5000A

Filter unique rows

(api/unique-by DS)

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C
(api/unique-by DS [:V1 :V4])

_unnamed [6 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C

Discard rows with missing values

(api/drop-missing DS)

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C

Other filters

(api/random DS 3) ;; 3 random rows

_unnamed [3 4]:

:V1:V2:V3:V4
240.5000A
261.500C
240.5000A
(api/random DS (/ (api/row-count DS) 2)) ;; fraction of random rows

_unnamed [5 4]:

:V1:V2:V3:V4
191.500C
110.5000A
170.5000A
281.000B
221.000B
(api/by-rank DS :V1 zero?) ;; take top n entries

_unnamed [4 4]:

:V1:V2:V3:V4
221.000B
240.5000A
261.500C
281.000B

Convenience functions

(api/select-rows DS (comp (partial re-matches #"^B") str :V4))

_unnamed [3 4]:

:V1:V2:V3:V4
221.000B
151.000B
281.000B
(api/select-rows DS (comp #(<= 3 % 5) :V2))

_unnamed [3 4]:

:V1:V2:V3:V4
131.500C
240.5000A
151.000B
(api/select-rows DS (comp #(< 3 % 5) :V2))

_unnamed [1 4]:

:V1:V2:V3:V4
240.5000A
(api/select-rows DS (comp #(<= 3 % 5) :V2))

_unnamed [3 4]:

:V1:V2:V3:V4
131.500C
240.5000A
151.000B

Last example skipped.

Sort rows

Sort rows by column

(api/order-by DS :V3)

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
240.5000A
170.5000A
221.000B
151.000B
281.000B
131.500C
261.500C
191.500C

Sort rows in decreasing order

(api/order-by DS :V3 :desc)

_unnamed [9 4]:

:V1:V2:V3:V4
131.500C
261.500C
191.500C
151.000B
221.000B
281.000B
170.5000A
240.5000A
110.5000A

Sort rows based on several columns

(api/order-by DS [:V1 :V2] [:asc :desc])

_unnamed [9 4]:

:V1:V2:V3:V4
191.500C
170.5000A
151.000B
131.500C
110.5000A
281.000B
261.500C
240.5000A
221.000B
Select columns

Select one column using an index (not recommended)

(nth (api/columns DS :as-seq) 2) ;; as column (iterable)
#tech.ml.dataset.column<float64>[9]
:V3
[0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, 0.5000, 1.000, 1.500, ]
(api/dataset [(nth (api/columns DS :as-seq) 2)])

_unnamed [9 1]:

:V3
0.5000
1.000
1.500
0.5000
1.000
1.500
0.5000
1.000
1.500

Select one column using column name

(api/select-columns DS :V2) ;; as dataset

_unnamed [9 1]:

:V2
1
2
3
4
5
6
7
8
9
(api/select-columns DS [:V2]) ;; as dataset

_unnamed [9 1]:

:V2
1
2
3
4
5
6
7
8
9
(DS :V2) ;; as column (iterable)
#tech.ml.dataset.column<int64>[9]
:V2
[1, 2, 3, 4, 5, 6, 7, 8, 9, ]

Select several columns

(api/select-columns DS [:V2 :V3 :V4])

_unnamed [9 3]:

:V2:V3:V4
10.5000A
21.000B
31.500C
40.5000A
51.000B
61.500C
70.5000A
81.000B
91.500C

Exclude columns

(api/select-columns DS (complement #{:V2 :V3 :V4}))

_unnamed [9 1]:

:V1
1
2
1
2
1
2
1
2
1
(api/drop-columns DS [:V2 :V3 :V4])

_unnamed [9 1]:

:V1
1
2
1
2
1
2
1
2
1

Other seletions

(->> (range 1 3)
     (map (comp keyword (partial format "V%d")))
     (api/select-columns DS))

_unnamed [9 2]:

:V1:V2
11
22
13
24
15
26
17
28
19
(api/reorder-columns DS :V4)

_unnamed [9 4]:

:V4:V1:V2:V3
A110.5000
B221.000
C131.500
A240.5000
B151.000
C261.500
A170.5000
B281.000
C191.500
(api/select-columns DS #(clojure.string/starts-with? (name %) "V"))

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
221.000B
131.500C
240.5000A
151.000B
261.500C
170.5000A
281.000B
191.500C
(api/select-columns DS #(clojure.string/ends-with? (name %) "3"))

_unnamed [9 1]:

:V3
0.5000
1.000
1.500
0.5000
1.000
1.500
0.5000
1.000
1.500
(api/select-columns DS #"..2") ;; regex converts to string using `str` function

_unnamed [9 1]:

:V2
1
2
3
4
5
6
7
8
9
(api/select-columns DS #{:V1 "X"})

_unnamed [9 1]:

:V1
1
2
1
2
1
2
1
2
1
(api/select-columns DS #(not (clojure.string/starts-with? (name %) "V2")))

_unnamed [9 3]:

:V1:V3:V4
10.5000A
21.000B
11.500C
20.5000A
11.000B
21.500C
10.5000A
21.000B
11.500C
Summarise data

Summarise one column

(reduce + (DS :V1)) ;; using pure Clojure, as value
13
(api/aggregate-columns DS :V1 dfn/sum) ;; as dataset

_unnamed [1 1]:

:V1
13.00
(api/aggregate DS {:sumV1 #(dfn/sum (% :V1))})

_unnamed [1 1]:

:sumV1
13.00

Summarize several columns

(api/aggregate DS [#(dfn/sum (% :V1))
                   #(dfn/standard-deviation (% :V3))])

_unnamed [1 2]:

:summary-0:summary-1
13.000.4330
(api/aggregate-columns DS [:V1 :V3] [dfn/sum
                                     dfn/standard-deviation])

_unnamed [1 2]:

:V1:V3
13.000.4330

Summarise several columns and assign column names

(api/aggregate DS {:sumv1 #(dfn/sum (% :V1))
                   :sdv3 #(dfn/standard-deviation (% :V3))})

_unnamed [1 2]:

:sumv1:sdv3
13.000.4330

Summarise a subset of rows

(-> DS
    (api/select-rows (range 4))
    (api/aggregate-columns :V1 dfn/sum))

_unnamed [1 1]:

:V1
6.000
Additional helpers
(-> DS
    (api/first)
    (api/select-columns :V3)) ;; select first row from `:V3` column

_unnamed [1 1]:

:V3
0.5000
(-> DS
    (api/last)
    (api/select-columns :V3)) ;; select last row from `:V3` column

_unnamed [1 1]:

:V3
1.500
(-> DS
    (api/select-rows 4)
    (api/select-columns :V3)) ;; select forth row from `:V3` column

_unnamed [1 1]:

:V3
1.000
(-> DS
    (api/select :V3 4)) ;; select forth row from `:V3` column

_unnamed [1 1]:

:V3
1.000
(-> DS
    (api/unique-by :V4)
    (api/aggregate api/row-count)) ;; number of unique rows in `:V4` column, as dataset

_unnamed [1 1]:

:summary
3
(-> DS
    (api/unique-by :V4)
    (api/row-count)) ;; number of unique rows in `:V4` column, as value
3
(-> DS
    (api/unique-by)
    (api/row-count)) ;; number of unique rows in dataset, as value
9
Add/update/delete columns

Modify a column

(api/map-columns DS :V1 [:V1] #(dfn/pow % 2))

_unnamed [9 4]:

:V1:V2:V3:V4
110.5000A
421.000B
131.500C
440.5000A
151.000B
461.500C
170.5000A
481.000B
191.500C
(def DS (api/add-or-replace-column DS :V1 (dfn/pow (DS :V1) 2)))
DS

_unnamed [9 4]:

:V1:V2:V3:V4
1.00010.5000A
4.00021.000B
1.00031.500C
4.00040.5000A
1.00051.000B
4.00061.500C
1.00070.5000A
4.00081.000B
1.00091.500C

Add one column

(api/map-columns DS :v5 [:V1] dfn/log)

_unnamed [9 5]:

:V1:V2:V3:V4:v5
1.00010.5000A0.000
4.00021.000B1.386
1.00031.500C0.000
4.00040.5000A1.386
1.00051.000B0.000
4.00061.500C1.386
1.00070.5000A0.000
4.00081.000B1.386
1.00091.500C0.000
(def DS (api/add-or-replace-column DS :v5 (dfn/log (DS :V1))))
DS

_unnamed [9 5]:

:V1:V2:V3:V4:v5
1.00010.5000A0.000
4.00021.000B1.386
1.00031.500C0.000
4.00040.5000A1.386
1.00051.000B0.000
4.00061.500C1.386
1.00070.5000A0.000
4.00081.000B1.386
1.00091.500C0.000

Add several columns

(def DS (api/add-or-replace-columns DS {:v6 (dfn/sqrt (DS :V1))
                                       :v7 "X"}))
DS

_unnamed [9 7]:

:V1:V2:V3:V4:v5:v6:v7
1.00010.5000A0.0001.000X
4.00021.000B1.3862.000X
1.00031.500C0.0001.000X
4.00040.5000A1.3862.000X
1.00051.000B0.0001.000X
4.00061.500C1.3862.000X
1.00070.5000A0.0001.000X
4.00081.000B1.3862.000X
1.00091.500C0.0001.000X

Create one column and remove the others

(api/dataset {:v8 (dfn/+ (DS :V3) 1)})

_unnamed [9 1]:

:v8
1.500
2.000
2.500
1.500
2.000
2.500
1.500
2.000
2.500

Remove one column

(def DS (api/drop-columns DS :v5))
DS

_unnamed [9 6]:

:V1:V2:V3:V4:v6:v7
1.00010.5000A1.000X
4.00021.000B2.000X
1.00031.500C1.000X
4.00040.5000A2.000X
1.00051.000B1.000X
4.00061.500C2.000X
1.00070.5000A1.000X
4.00081.000B2.000X
1.00091.500C1.000X

Remove several columns

(def DS (api/drop-columns DS [:v6 :v7]))
DS

_unnamed [9 4]:

:V1:V2:V3:V4
1.00010.5000A
4.00021.000B
1.00031.500C
4.00040.5000A
1.00051.000B
4.00061.500C
1.00070.5000A
4.00081.000B
1.00091.500C

Remove columns using a vector of colnames

We use set here.

(def DS (api/select-columns DS (complement #{:V3})))
DS

_unnamed [9 3]:

:V1:V2:V4
1.0001A
4.0002B
1.0003C
4.0004A
1.0005B
4.0006C
1.0007A
4.0008B
1.0009C

Replace values for rows matching a condition

(def DS (api/map-columns DS :V2 [:V2] #(if (< % 4.0) 0.0 %)))
DS

_unnamed [9 3]:

:V1:V2:V4
1.0000A
4.0000B
1.0000C
4.0004A
1.0005B
4.0006C
1.0007A
4.0008B
1.0009C
by

By group

(-> DS
    (api/group-by [:V4])
    (api/aggregate {:sumV2 #(dfn/sum (% :V2))}))

_unnamed [3 2]:

:V4:sumV2
B13.00
C15.00
A11.00

By several groups

(-> DS
    (api/group-by [:V4 :V1])
    (api/aggregate {:sumV2 #(dfn/sum (% :V2))}))

_unnamed [6 3]:

:V4:V1:sumV2
A4.0004.000
A1.0007.000
B1.0005.000
B4.0008.000
C4.0006.000
C1.0009.000

Calling function in by

(-> DS
    (api/group-by (fn [row]
                    (clojure.string/lower-case (:V4 row))))
    (api/aggregate {:sumV1 #(dfn/sum (% :V1))}))

_unnamed [3 2]:

:$group-name:sumV1
a6.000
b9.000
c6.000

Assigning column name in by

(-> DS
    (api/group-by (fn [row]
                    {:abc (clojure.string/lower-case (:V4 row))}))
    (api/aggregate {:sumV1 #(dfn/sum (% :V1))}))

_unnamed [3 2]:

:abc:sumV1
a6.000
b9.000
c6.000
(-> DS
    (api/group-by (fn [row]
                    (clojure.string/lower-case (:V4 row))))
    (api/aggregate {:sumV1 #(dfn/sum (% :V1))} {:add-group-as-column :abc}))

_unnamed [3 2]:

:abc:sumV1
a6.000
b9.000
c6.000

Using a condition in by

(-> DS
    (api/group-by #(= (:V4 %) "A"))
    (api/aggregate #(dfn/sum (% :V1))))

_unnamed [2 2]:

:$group-name:summary
false15.00
true6.000

By on a subset of rows

(-> DS
    (api/select-rows (range 5))
    (api/group-by :V4)
    (api/aggregate {:sumV1 #(dfn/sum (% :V1))}))

_unnamed [3 2]:

:$group-name:sumV1
A5.000
B5.000
C1.000

Count number of observations for each group

(-> DS
    (api/group-by :V4)
    (api/aggregate api/row-count))

_unnamed [3 2]:

:$group-name:summary
A3
B3
C3

Add a column with number of observations for each group

(-> DS
    (api/group-by [:V1])
    (api/add-or-replace-column :n api/row-count)
    (api/ungroup))

_unnamed [9 4]:

:V1:V2:V4:n
4.0000B4
4.0004A4
4.0006C4
4.0008B4
1.0000A5
1.0000C5
1.0005B5
1.0007A5
1.0009C5

Retrieve the first/last/nth observation for each group

(-> DS
    (api/group-by [:V4])
    (api/aggregate-columns :V2 first))

_unnamed [3 2]:

:V4:V2
B0
C0
A0
(-> DS
    (api/group-by [:V4])
    (api/aggregate-columns :V2 last))

_unnamed [3 2]:

:V4:V2
B8
C9
A7
(-> DS
    (api/group-by [:V4])
    (api/aggregate-columns :V2 #(nth % 1)))

_unnamed [3 2]:

:V4:V2
B5
C6
A4

Going further

Advanced columns manipulation

Summarise all the columns

;; custom max function which works on every type
(api/aggregate-columns DS :all (fn [col] (first (sort #(compare %2 %1) col))))

_unnamed [1 3]:

:V1:V2:V4
4.0009C

Summarise several columns

(api/aggregate-columns DS [:V1 :V2] dfn/mean)

_unnamed [1 2]:

:V1:V2
2.3334.333

Summarise several columns by group

(-> DS
    (api/group-by [:V4])
    (api/aggregate-columns [:V1 :V2] dfn/mean))

_unnamed [3 3]:

:V4:V1:V2
B3.0004.333
C2.0005.000
A2.0003.667

Summarise with more than one function by group

(-> DS
    (api/group-by [:V4])
    (api/aggregate-columns [:V1 :V2] (fn [col]
                                       {:sum (dfn/sum col)
                                        :mean (dfn/mean col)})))

_unnamed [3 5]:

:V4:V1-sum:V1-mean:V2-sum:V2-mean
B9.0003.00013.004.333
C6.0002.00015.005.000
A6.0002.00011.003.667

Summarise using a condition

(-> DS
    (api/select-columns :type/numerical)
    (api/aggregate-columns :all dfn/mean))

_unnamed [1 2]:

:V1:V2
2.3334.333

Modify all the columns

(api/update-columns DS :all reverse)

_unnamed [9 3]:

:V1:V2:V4
1.0009C
4.0008B
1.0007A
4.0006C
1.0005B
4.0004A
1.0000C
4.0000B
1.0000A

Modify several columns (dropping the others)

(-> DS
    (api/select-columns [:V1 :V2])
    (api/update-columns :all dfn/sqrt))

_unnamed [9 2]:

:V1:V2
1.0000.000
2.0000.000
1.0000.000
2.0002.000
1.0002.236
2.0002.449
1.0002.646
2.0002.828
1.0003.000
(-> DS
    (api/select-columns (complement #{:V4}))
    (api/update-columns :all dfn/exp))

_unnamed [9 2]:

:V1:V2
2.7181.000
54.601.000
2.7181.000
54.6054.60
2.718148.4
54.60403.4
2.7181097
54.602981
2.7188103

Modify several columns (keeping the others)

(def DS (api/update-columns DS [:V1 :V2] dfn/sqrt))
DS

_unnamed [9 3]:

:V1:V2:V4
1.0000.000A
2.0000.000B
1.0000.000C
2.0002.000A
1.0002.236B
2.0002.449C
1.0002.646A
2.0002.828B
1.0003.000C
(def DS (api/update-columns DS (complement #{:V4}) #(dfn/pow % 2)))
DS

_unnamed [9 3]:

:V1:V2:V4
1.0000.000A
4.0000.000B
1.0000.000C
4.0004.000A
1.0005.000B
4.0006.000C
1.0007.000A
4.0008.000B
1.0009.000C

Modify columns using a condition (dropping the others)

(-> DS
    (api/select-columns :type/numerical)
    (api/update-columns :all #(dfn/- % 1)))

_unnamed [9 2]:

:V1:V2
0.000-1.000
3.000-1.000
0.000-1.000
3.0003.000
0.0004.000
3.0005.000
0.0006.000
3.0007.000
0.0008.000

Modify columns using a condition (keeping the others)

(def DS (api/convert-types DS :type/numerical :int32))
DS

_unnamed [9 3]:

:V1:V2:V4
10A
40B
10C
44A
15B
45C
17A
48B
19C

Use a complex expression

(-> DS
    (api/group-by [:V4])
    (api/head 2)
    (api/add-or-replace-column :V2 "X")
    (api/ungroup))

_unnamed [6 3]:

:V1:V2:V4
4XB
1XB
1XC
4XC
1XA
4XA

Use multiple expressions

(api/dataset (let [x (dfn/+ (DS :V1) (dfn/sum (DS :V2)))]
               (println (seq (DS :V1)))
               (println (api/info (api/select-columns DS :V1)))
               {:A (range 1 (inc (api/row-count DS)))
                :B x}))

(1 4 1 4 1 4 1 4 1) _unnamed: descriptive-stats [1 9]:

:col-name:datatype:n-valid:n-missing:min:mean:max:standard-deviation:skew
:V1:int32901.0002.3334.0001.5810.2711

_unnamed [9 2]:

:A:B
139.00
242.00
339.00
442.00
539.00
642.00
739.00
842.00
939.00
Chain expressions

Expression chaining using >

(-> DS
    (api/group-by [:V4])
    (api/aggregate {:V1sum #(dfn/sum (% :V1))})
    (api/select-rows #(> (:V1sum %) 5) ))

_unnamed [3 2]:

:V4:V1sum
B9.000
C6.000
A6.000
(-> DS
    (api/group-by [:V4])
    (api/aggregate {:V1sum #(dfn/sum (% :V1))})
    (api/order-by :V1sum :desc))

_unnamed [3 2]:

:V4:V1sum
B9.000
C6.000
A6.000
Indexing and Keys

Set the key/index (order)

(def DS (api/order-by DS :V4))
DS

_unnamed [9 3]:

:V1:V2:V4
10A
44A
17A
40B
15B
48B
10C
45C
19C

Select the matching rows

(api/select-rows DS #(= (:V4 %) "A"))

_unnamed [3 3]:

:V1:V2:V4
10A
44A
17A
(api/select-rows DS (comp #{"A" "C"} :V4))

_unnamed [6 3]:

:V1:V2:V4
10A
44A
17A
10C
45C
19C

Select the first matching row

(-> DS
    (api/select-rows #(= (:V4 %) "B"))
    (api/first))

_unnamed [1 3]:

:V1:V2:V4
40B
(-> DS
    (api/unique-by :V4)
    (api/select-rows (comp #{"B" "C"} :V4)))

_unnamed [2 3]:

:V1:V2:V4
40B
10C

Select the last matching row

(-> DS
    (api/select-rows #(= (:V4 %) "A"))
    (api/last))

_unnamed [1 3]:

:V1:V2:V4
17A

Nomatch argument

(api/select-rows DS (comp #{"A" "D"} :V4))

_unnamed [3 3]:

:V1:V2:V4
10A
44A
17A

Apply a function on the matching rows

(-> DS
    (api/select-rows (comp #{"A" "C"} :V4))
    (api/aggregate-columns :V1 (fn [col]
                                 {:sum (dfn/sum col)})))

_unnamed [1 1]:

:V1-sum
12.00

Modify values for matching rows

(def DS (-> DS
            (api/map-columns :V1 [:V1 :V4] #(if (= %2 "A") 0 %1))
            (api/order-by :V4)))
DS

_unnamed [9 3]:

:V1:V2:V4
00A
04A
07A
40B
15B
48B
10C
45C
19C

Use keys in by

(-> DS
    (api/select-rows (comp (complement #{"B"}) :V4))
    (api/group-by [:V4])
    (api/aggregate-columns :V1 dfn/sum))

_unnamed [2 2]:

:V4:V1
C6.000
A0.000

Set keys/indices for multiple columns (ordered)

(api/order-by DS [:V4 :V1])

_unnamed [9 3]:

:V1:V2:V4
00A
04A
07A
15B
40B
48B
10C
19C
45C

Subset using multiple keys/indices

(-> DS
    (api/select-rows #(and (= (:V1 %) 1)
                           (= (:V4 %) "C"))))

_unnamed [2 3]:

:V1:V2:V4
10C
19C
(-> DS
    (api/select-rows #(and (= (:V1 %) 1)
                           (#{"B" "C"} (:V4 %)))))

_unnamed [3 3]:

:V1:V2:V4
15B
10C
19C
(-> DS
    (api/select-rows #(and (= (:V1 %) 1)
                           (#{"B" "C"} (:V4 %))) {:result-type :as-indexes}))
(4 6 8)
set*() modifications

Replace values

There is no mutating operations tech.ml.dataset or easy way to set value.

(def DS (api/update-columns DS :V2 #(map-indexed (fn [idx v]
                                                   (if (zero? idx) 3 v)) %)))
DS

_unnamed [9 3]:

:V1:V2:V4
03A
04A
07A
40B
15B
48B
10C
45C
19C

Reorder rows

(def DS (api/order-by DS [:V4 :V1] [:asc :desc]))
DS

_unnamed [9 3]:

:V1:V2:V4
03A
04A
07A
40B
48B
15B
45C
10C
19C

Modify colnames

(def DS (api/rename-columns DS {:V2 "v2"}))
DS

_unnamed [9 3]:

:V1v2:V4
03A
04A
07A
40B
48B
15B
45C
10C
19C
(def DS (api/rename-columns DS {"v2" :V2})) ;; revert back

Reorder columns

(def DS (api/reorder-columns DS :V4 :V1 :V2))
DS

_unnamed [9 3]:

:V4:V1:V2
A03
A04
A07
B40
B48
B15
C45
C10
C19
Advanced use of by

Select first/last/… row by group

(-> DS
    (api/group-by :V4)
    (api/first)
    (api/ungroup))

_unnamed [3 3]:

:V4:V1:V2
A03
B40
C45
(-> DS
    (api/group-by :V4)
    (api/select-rows [0 2])
    (api/ungroup))

_unnamed [6 3]:

:V4:V1:V2
A03
A07
B40
B15
C45
C19
(-> DS
    (api/group-by :V4)
    (api/tail 2)
    (api/ungroup))

_unnamed [6 3]:

:V4:V1:V2
A04
A07
B48
B15
C10
C19

Select rows using a nested query

(-> DS
    (api/group-by :V4)
    (api/order-by :V2)
    (api/first)
    (api/ungroup))

_unnamed [3 3]:

:V4:V1:V2
A03
B40
C10

Add a group counter column

(-> DS
    (api/group-by [:V4 :V1])
    (api/ungroup {:add-group-id-as-column :Grp}))

_unnamed [9 4]:

:Grp:V4:V1:V2
0A03
0A04
0A07
1B15
2C10
2C19
3B40
3B48
4C45

Get row number of first (and last) observation by group

(-> DS
    (api/add-or-replace-column :row-id (range))
    (api/select-columns [:V4 :row-id])
    (api/group-by :V4)
    (api/ungroup))

_unnamed [9 2]:

:V4:row-id
A0
A1
A2
B3
B4
B5
C6
C7
C8
(-> DS
    (api/add-or-replace-column :row-id (range))
    (api/select-columns [:V4 :row-id])
    (api/group-by :V4)
    (api/first)
    (api/ungroup))

_unnamed [3 2]:

:V4:row-id
A0
B3
C6
(-> DS
    (api/add-or-replace-column :row-id (range))
    (api/select-columns [:V4 :row-id])
    (api/group-by :V4)
    (api/select-rows [0 2])
    (api/ungroup))

_unnamed [6 2]:

:V4:row-id
A0
A2
B3
B5
C6
C8

Handle list-columns by group

(-> DS
    (api/select-columns [:V1 :V4])
    (api/fold-by :V4))

_unnamed [3 2]:

:V4:V1
B[4 4 1]
C[4 1 1]
A[0 0 0]
(-> DS    
    (api/group-by :V4)
    (api/unmark-group))

_unnamed [3 3]:

:name:group-id:data
A0Group: A [3 3]:
B1Group: B [3 3]:
C2Group: C [3 3]:

Grouping sets (multiple by at once)

Not available.

Miscellaneous

Read / Write data

Write data to a csv file

(api/write-csv! DS "DF.csv")
nil

Write data to a tab-delimited file

(api/write-csv! DS "DF.txt" {:separator \tab})
nil

or

(api/write-csv! DS "DF.tsv")
nil

Read a csv / tab-delimited file

(api/dataset "DF.csv" {:key-fn keyword})

DF.csv [9 3]:

:V4:V1:V2
A03
A04
A07
B40
B48
B15
C45
C10
C19
(api/dataset "DF.txt" {:key-fn keyword})

DF.txt [9 3]:

:V4:V1:V2
A03
A04
A07
B40
B48
B15
C45
C10
C19
(api/dataset "DF.tsv" {:key-fn keyword})

DF.tsv [9 3]:

:V4:V1:V2
A03
A04
A07
B40
B48
B15
C45
C10
C19

Read a csv file selecting / droping columns

(api/dataset "DF.csv" {:key-fn keyword
                       :column-whitelist ["V1" "V4"]})

DF.csv [9 2]:

:V1:V4
0A
0A
0A
4B
4B
1B
4C
1C
1C
(api/dataset "DF.csv" {:key-fn keyword
                       :column-blacklist ["V4"]})

DF.csv [9 2]:

:V1:V2
03
04
07
40
48
15
45
10
19

Read and rbind several files

(apply api/concat (map api/dataset ["DF.csv" "DF.csv"]))

null [18 3]:

V4V1V2
A03
A04
A07
B40
B48
B15
C45
C10
C19
A03
A04
A07
B40
B48
B15
C45
C10
C19
Reshape data

Melt data (from wide to long)

(def mDS (api/pivot->longer DS [:V1 :V2] {:target-columns :variable
                                          :value-column-name :value}))
mDS

_unnamed [18 3]:

:V4:variable:value
A:V10
A:V10
A:V10
B:V14
B:V14
B:V11
C:V14
C:V11
C:V11
A:V23
A:V24
A:V27
B:V20
B:V28
B:V25
C:V25
C:V20
C:V29

Cast data (from long to wide)

(-> mDS
    (api/pivot->wider :variable :value {:fold-fn vec})
    (api/update-columns [:V1 :V2] (partial map count)))

_unnamed [3 3]:

:V4:V1:V2
C33
B33
A33
(-> mDS
    (api/pivot->wider :variable :value {:fold-fn vec})
    (api/update-columns [:V1 :V2] (partial map dfn/sum)))

_unnamed [3 3]:

:V4:V1:V2
C6.00014.00
B9.00013.00
A0.00014.00
(-> mDS
    (api/map-columns :value #(> % 5))
    (api/pivot->wider :value :variable {:fold-fn vec})
    (api/update-columns [true false] (partial map #(if (sequential? %) (count %) 1))))

_unnamed [3 3]:

:V4truefalse
A15
B15
C15

Split

(api/group-by DS :V4 {:result-type :as-map})

{"A" Group: A [3 3]:

:V4:V1:V2
A03
A04
A07

, "B" Group: B [3 3]:

:V4:V1:V2
B40
B48
B15

, "C" Group: C [3 3]:

:V4:V1:V2
C45
C10
C19

}


Split and transpose a vector/column

(-> {:a ["A:a" "B:b" "C:c"]}
    (api/dataset)
    (api/separate-column :a [:V1 :V2] ":"))

_unnamed [3 2]:

:V1:V2
Aa
Bb
Cc
Other

Skipped

Join/Bind data sets

(def x (api/dataset {"Id" ["A" "B" "C" "C"]
                     "X1" [1 3 5 7]
                     "XY" ["x2" "x4" "x6" "x8"]}))
(def y (api/dataset {"Id" ["A" "B" "B" "D"]
                     "Y1" [1 3 5 7]
                     "XY" ["y1" "y3" "y5" "y7"]}))
x y

_unnamed [4 3]:

IdX1XY
A1x2
B3x4
C5x6
C7x8

_unnamed [4 3]:

IdY1XY
A1y1
B3y3
B5y5
D7y7
Join

Join matching rows from y to x

(api/left-join x y "Id")

left-outer-join [5 6]:

IdX1XYright.IdY1right.XY
A1x2A1y1
B3x4B3y3
B3x4B5y5
C5x6
C7x8

Join matching rows from x to y

(api/right-join x y "Id")

right-outer-join [4 6]:

IdX1XYright.IdY1right.XY
A1x2A1y1
B3x4B3y3
B3x4B5y5
D7y7

Join matching rows from both x and y

(api/inner-join x y "Id")

inner-join [3 5]:

IdX1XYY1right.XY
A1x21y1
B3x43y3
B3x45y5

Join keeping all the rows

(api/full-join x y "Id")

full-join [6 6]:

IdX1XYright.IdY1right.XY
A1x2A1y1
B3x4B3y3
B3x4B5y5
C5x6
C7x8
D7y7

Return rows from x matching y

(api/semi-join x y "Id")

semi-join [2 3]:

IdX1XY
A1x2
B3x4

Return rows from x not matching y

(api/anti-join x y "Id")

anti-join [2 3]:

IdX1XY
C5x6
C7x8
More joins

Select columns while joining

(api/right-join (api/select-columns x ["Id" "X1"])
                (api/select-columns y ["Id" "XY"])
                "Id")

right-outer-join [4 4]:

IdX1right.IdXY
A1Ay1
B3By3
B3By5
Dy7
(api/right-join (api/select-columns x ["Id" "XY"])
                (api/select-columns y ["Id" "XY"])
                "Id")

right-outer-join [4 4]:

IdXYright.Idright.XY
Ax2Ay1
Bx4By3
Bx4By5
Dy7

Aggregate columns while joining

(-> y
    (api/group-by ["Id"])
    (api/aggregate {"sumY1" #(dfn/sum (% "Y1"))})
    (api/right-join x "Id")
    (api/add-or-replace-column "X1Y1" (fn [ds] (dfn/* (ds "sumY1")
                                                    (ds "X1"))))
    (api/select-columns ["right.Id" "X1Y1"]))

right-outer-join [4 2]:

right.IdX1Y1
A1.000
B24.00
CNAN
CNAN

Update columns while joining

(-> x
    (api/select-columns ["Id" "X1"])
    (api/map-columns "SqX1" "X1" (fn [x] (* x x)))
    (api/right-join y "Id")
    (api/drop-columns ["X1" "Id"]))

right-outer-join [4 4]:

SqX1right.IdY1XY
1A1y1
9B3y3
9B5y5
D7y7

Adds a list column with rows from y matching x (nest-join)

(-> (api/left-join x y "Id")
    (api/drop-columns ["right.Id"])
    (api/fold-by (api/column-names x)))

_unnamed [4 5]:

XYX1IdY1right.XY
x43B[3 5]["y3" "y5"]
x65C[][]
x87C[][]
x21A[1]["y1"]

Some joins are skipped


Cross join

(def cjds (api/dataset {:V1 [[2 1 1]]
                        :V2 [[3 2]]}))
cjds

_unnamed [1 2]:

:V1:V2
[2 1 1][3 2]
(reduce #(api/unroll %1 %2) cjds (api/column-names cjds))

_unnamed [6 2]:

:V1:V2
23
22
13
12
13
12
(-> (reduce #(api/unroll %1 %2) cjds (api/column-names cjds))
    (api/unique-by))

_unnamed [4 2]:

:V1:V2
23
22
13
12
Bind
(def x (api/dataset {:V1 [1 2 3]}))
(def y (api/dataset {:V1 [4 5 6]}))
(def z (api/dataset {:V1 [7 8 9]
                     :V2 [0 0 0]}))
x y z

_unnamed [3 1]:

:V1
1
2
3

_unnamed [3 1]:

:V1
4
5
6

_unnamed [3 2]:

:V1:V2
70
80
90

Bind rows

(api/bind x y)

null [6 1]:

:V1
1
2
3
4
5
6
(api/bind x z)

null [6 2]:

:V1:V2
1
2
3
70
80
90

Bind rows using a list

(->> [x y]
     (map-indexed #(api/add-or-replace-column %2 :id (repeat %1)))
     (apply api/bind))

null [6 2]:

:V1:id
10
20
30
41
51
61

Bind columns

(api/append x y)

_unnamed [3 2]:

:V1:V1
14
25
36
Set operations
(def x (api/dataset {:V1 [1 2 2 3 3]}))
(def y (api/dataset {:V1 [2 2 3 4 4]}))
x y

_unnamed [5 1]:

:V1
1
2
2
3
3

_unnamed [5 1]:

:V1
2
2
3
4
4

Intersection

(api/intersect x y)

intersection [2 1]:

:V1
2
3

Difference

(api/difference x y)

difference [1 1]:

:V1
1

Union

(api/union x y)

union [4 1]:

:V1
1
2
3
4
(api/concat x y)

null [10 1]:

:V1
1
2
2
3
3
2
2
3
4
4

Equality not implemented

Can you improve this documentation?Edit on GitHub

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close