Transformation to DataFrames#

Split-apply-combine

using DataFrames

Grouping a data frame#

groupby

x = DataFrame(id=[1, 2, 3, 4, 1, 2, 3, 4], id2=[1, 2, 1, 2, 1, 2, 1, 2], v=rand(8))
8×3 DataFrame
Rowidid2v
Int64Int64Float64
1110.325215
2220.369038
3310.814633
4420.377291
5110.0800426
6220.796786
7310.21076
8420.75457
groupby(x, :id)

GroupedDataFrame with 4 groups based on key: id

First Group (2 rows): id = 1
Rowidid2v
Int64Int64Float64
1110.325215
2110.0800426

Last Group (2 rows): id = 4
Rowidid2v
Int64Int64Float64
1420.377291
2420.75457
groupby(x, [])

GroupedDataFrame with 1 group based on key:

First Group (8 rows):
Rowidid2v
Int64Int64Float64
1110.325215
2220.369038
3310.814633
4420.377291
5110.0800426
6220.796786
7310.21076
8420.75457
gx2 = groupby(x, [:id, :id2])

GroupedDataFrame with 4 groups based on keys: id, id2

First Group (2 rows): id = 1, id2 = 1
Rowidid2v
Int64Int64Float64
1110.325215
2110.0800426

Last Group (2 rows): id = 4, id2 = 2
Rowidid2v
Int64Int64Float64
1420.377291
2420.75457

get the parent DataFrame

parent(gx2)
8×3 DataFrame
Rowidid2v
Int64Int64Float64
1110.325215
2220.369038
3310.814633
4420.377291
5110.0800426
6220.796786
7310.21076
8420.75457

back to the DataFrame, but in a different order of rows than the original

vcat(gx2...)
8×3 DataFrame
Rowidid2v
Int64Int64Float64
1110.325215
2110.0800426
3220.369038
4220.796786
5310.814633
6310.21076
7420.377291
8420.75457

the same as above

DataFrame(gx2)
8×3 DataFrame
Rowidid2v
Int64Int64Float64
1110.325215
2110.0800426
3220.369038
4220.796786
5310.814633
6310.21076
7420.377291
8420.75457

drop grouping columns when creating a data frame

DataFrame(gx2, keepkeys=false)
8×1 DataFrame
Rowv
Float64
10.325215
20.0800426
30.369038
40.796786
50.814633
60.21076
70.377291
80.75457

vector of names of grouping variables

groupcols(gx2)
2-element Vector{Symbol}:
 :id
 :id2

and non-grouping variables

valuecols(gx2)
1-element Vector{Symbol}:
 :v

group indices in parent(gx2)

groupindices(gx2)
8-element Vector{Union{Missing, Int64}}:
 1
 2
 3
 4
 1
 2
 3
 4
kgx2 = keys(gx2)
4-element DataFrames.GroupKeys{DataFrames.GroupedDataFrame{DataFrames.DataFrame}}:
 GroupKey: (id = 1, id2 = 1)
 GroupKey: (id = 2, id2 = 2)
 GroupKey: (id = 3, id2 = 1)
 GroupKey: (id = 4, id2 = 2)

You can index into a GroupedDataFrame like to a vector or to a dictionary. The second form accepts GroupKey, NamedTuple or a Tuple.

gx2

GroupedDataFrame with 4 groups based on keys: id, id2

First Group (2 rows): id = 1, id2 = 1
Rowidid2v
Int64Int64Float64
1110.325215
2110.0800426

Last Group (2 rows): id = 4, id2 = 2
Rowidid2v
Int64Int64Float64
1420.377291
2420.75457
k = keys(gx2)[1]
GroupKey: (id = 1, id2 = 1)
ntk = NamedTuple(k)
(id = 1, id2 = 1)
tk = Tuple(k)
(1, 1)

the operations below produce the same result and are proformant

gx2[1], gx2[k], gx2[ntk], gx2[tk]
(2×3 SubDataFrame
 Row  id     id2    v         
     │ Int64  Int64  Float64   
─────┼─────────────────────────
   1 │     1      1  0.325215
   2 │     1      1  0.0800426, 2×3 SubDataFrame
 Row  id     id2    v         
     │ Int64  Int64  Float64   
─────┼─────────────────────────
   1 │     1      1  0.325215
   2 │     1      1  0.0800426, 2×3 SubDataFrame
 Row  id     id2    v         
     │ Int64  Int64  Float64   
─────┼─────────────────────────
   1 │     1      1  0.325215
   2 │     1      1  0.0800426, 2×3 SubDataFrame
 Row  id     id2    v         
     │ Int64  Int64  Float64   
─────┼─────────────────────────
   1 │     1      1  0.325215
   2 │     1      1  0.0800426)

handling missing values

x = DataFrame(id=[missing, 5, 1, 3, missing], x=1:5)
5×2 DataFrame
Rowidx
Int64?Int64
1missing1
252
313
434
5missing5

by default groups include missing values and their order is not guaranteed

groupby(x, :id)

GroupedDataFrame with 4 groups based on key: id

First Group (1 row): id = 1
Rowidx
Int64?Int64
113

Last Group (2 rows): id = missing
Rowidx
Int64?Int64
1missing1
2missing5

but we can change it; now they are sorted

groupby(x, :id, sort=true, skipmissing=true)

GroupedDataFrame with 3 groups based on key: id

First Group (1 row): id = 1
Rowidx
Int64?Int64
113

Last Group (1 row): id = 5
Rowidx
Int64?Int64
152

and now they are in the order they appear in the source data frame

groupby(x, :id, sort=false)

GroupedDataFrame with 4 groups based on key: id

First Group (2 rows): id = missing
Rowidx
Int64?Int64
1missing1
2missing5

Last Group (1 row): id = 3
Rowidx
Int64?Int64
134

Performing transformations#

by group using combine, select, select!, transform, and transform!

using Statistics
using Chain

x = DataFrame(id=rand('a':'d', 100), v=rand(100))
100×2 DataFrame
75 rows omitted
Rowidv
CharFloat64
1d0.911682
2a0.336318
3c0.569249
4a0.860833
5d0.990385
6d0.671075
7b0.456261
8a0.663899
9a0.673223
10c0.822798
11b0.948415
12d0.462216
13b0.772046
89b0.736596
90c0.010389
91d0.958571
92b0.132037
93c0.132203
94d0.6734
95c0.581931
96d0.732172
97a0.647178
98a0.746204
99a0.0444478
100c0.206397

apply a function to each group of a data frame combine keeps as many rows as are returned from the function

@chain x begin
    groupby(:id)
    combine(:v => mean)
end
4×2 DataFrame
Rowidv_mean
CharFloat64
1d0.579567
2a0.50468
3c0.512914
4b0.584901
x.id2 = axes(x, 1)
Base.OneTo(100)

Select and transform keep as many rows as are in the source data frame and in correct order. Additionally, transform keeps all columns from the source.

@chain x begin
    groupby(:id)
    transform(:v => mean)
end
100×4 DataFrame
75 rows omitted
Rowidvid2v_mean
CharFloat64Int64Float64
1d0.91168210.579567
2a0.33631820.50468
3c0.56924930.512914
4a0.86083340.50468
5d0.99038550.579567
6d0.67107560.579567
7b0.45626170.584901
8a0.66389980.50468
9a0.67322390.50468
10c0.822798100.512914
11b0.948415110.584901
12d0.462216120.579567
13b0.772046130.584901
89b0.736596890.584901
90c0.010389900.512914
91d0.958571910.579567
92b0.132037920.584901
93c0.132203930.512914
94d0.6734940.579567
95c0.581931950.512914
96d0.732172960.579567
97a0.647178970.50468
98a0.746204980.50468
99a0.0444478990.50468
100c0.2063971000.512914

note that combine reorders rows by group of GroupedDataFrame

@chain x begin
    groupby(:id)
    combine(:id2, :v => mean)
end
100×3 DataFrame
75 rows omitted
Rowidid2v_mean
CharInt64Float64
1d10.579567
2d50.579567
3d60.579567
4d120.579567
5d160.579567
6d220.579567
7d280.579567
8d300.579567
9d350.579567
10d370.579567
11d380.579567
12d390.579567
13d400.579567
89b580.584901
90b590.584901
91b640.584901
92b650.584901
93b690.584901
94b710.584901
95b740.584901
96b770.584901
97b840.584901
98b880.584901
99b890.584901
100b920.584901

we give a custom name for the result column

@chain x begin
    groupby(:id)
    combine(:v => mean => :res)
end
4×2 DataFrame
Rowidres
CharFloat64
1d0.579567
2a0.50468
3c0.512914
4b0.584901

you can have multiple operations

@chain x begin
    groupby(:id)
    combine(:v => mean => :res1, :v => sum => :res2, nrow => :n)
end
4×4 DataFrame
Rowidres1res2n
CharFloat64Float64Int64
1d0.57956715.648327
2a0.504689.0842418
3c0.51291413.848727
4b0.58490116.377228

Additional notes:

  • select! and transform! perform operations in-place

  • The general syntax for transformation is source_columns => function => target_column

  • if you pass multiple columns to a function they are treated as positional arguments

  • ByRow and AsTable work exactly like discussed for operations on data frames in 05_columns.ipynb

  • you can automatically groupby again the result of combine, select etc. by passing ungroup=false keyword argument to them

  • similarly keepkeys keyword argument allows you to drop grouping columns from the resulting data frame

It is also allowed to pass a function to all these functions (also - as a special case, as a first argument). In this case the return value can be a table. In particular it allows for an easy dropping of groups if you return an empty table from the function.

If you pass a function you can use a do block syntax. In case of passing a function it gets a SubDataFrame as its argument.

Here is an example:

combine(groupby(x, :id)) do sdf
    n = nrow(sdf)
    n < 25 ? DataFrame() : DataFrame(n=n) ## drop groups with low number of rows
end
3×2 DataFrame
Rowidn
CharInt64
1d27
2c27
3b28

You can also produce multiple columns in a single operation:

df = DataFrame(id=[1, 1, 2, 2], val=[1, 2, 3, 4])
4×2 DataFrame
Rowidval
Int64Int64
111
212
323
424
@chain df begin
    groupby(:id)
    combine(:val => (x -> [x]) => AsTable)
end
2×3 DataFrame
Rowidx1x2
Int64Int64Int64
1112
2234
@chain df begin
    groupby(:id)
    combine(:val => (x -> [x]) => [:c1, :c2])
end
2×3 DataFrame
Rowidc1c2
Int64Int64Int64
1112
2234

It is easy to unnest the column into multiple columns,

df = DataFrame(a=[(p=1, q=2), (p=3, q=4)])
select(df, :a => AsTable)
2×2 DataFrame
Rowpq
Int64Int64
112
234

automatic column names generated

df = DataFrame(a=[[1, 2], [3, 4]])
select(df, :a => AsTable)
2×2 DataFrame
Rowx1x2
Int64Int64
112
234

custom column names generated

select(df, :a => [:C1, :C2])
2×2 DataFrame
RowC1C2
Int64Int64
112
234

Finally, observe that one can conveniently apply multiple transformations using broadcasting:

df = DataFrame(id=repeat(1:10, 10), x1=1:100, x2=101:200)
100×3 DataFrame
75 rows omitted
Rowidx1x2
Int64Int64Int64
111101
222102
333103
444104
555105
666106
777107
888108
999109
101010110
11111111
12212112
13313113
89989189
901090190
91191191
92292192
93393193
94494194
95595195
96696196
97797197
98898198
99999199
10010100200
@chain df begin
    groupby(:id)
    combine([:x1, :x2] .=> minimum)
end
10×3 DataFrame
Rowidx1_minimumx2_minimum
Int64Int64Int64
111101
222102
333103
444104
555105
666106
777107
888108
999109
101010110
@chain df begin
    groupby(:id)
    combine([:x1, :x2] .=> [minimum maximum])
end
10×5 DataFrame
Rowidx1_minimumx2_minimumx1_maximumx2_maximum
Int64Int64Int64Int64Int64
11110191191
22210292192
33310393193
44410494194
55510595195
66610696196
77710797197
88810898198
99910999199
101010110100200

Aggregation of a data frame using mapcols#

x = DataFrame(rand(10, 10), :auto)
10×10 DataFrame
Rowx1x2x3x4x5x6x7x8x9x10
Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64
10.04977130.1740380.3356580.986170.8180460.3158020.1760870.886930.3314780.565418
20.4690670.5320940.5225630.6982940.6845670.7137360.2363390.4362620.4382890.501549
30.9607270.7927080.2195940.9918140.8530470.6613150.2278330.7966720.8305720.0412893
40.9543780.4641740.4694490.2071810.980270.8117470.9080940.1875830.1273470.11277
50.4904580.3560260.2200180.6729670.04627230.5789730.8383520.1452250.7189350.254138
60.2266930.9759310.824750.1329410.4861350.1893520.3053740.4785350.4571870.0475593
70.5205520.06622630.1543050.4401290.5082490.5319720.6040840.382340.6658010.563294
80.8811690.7825260.139470.5717470.2405820.5569180.9815250.8133370.079420.616259
90.6159440.7409410.1553280.4508760.7317920.4140140.9955690.8254180.8080660.795116
100.1715970.9279980.9452040.7617210.0007961490.7003390.8242260.7868920.336510.839618
mapcols(mean, x)
1×10 DataFrame
Rowx1x2x3x4x5x6x7x8x9x10
Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64
10.5340360.5812660.3986340.5913840.5349760.5474170.6097480.5739190.4793610.433701

Mapping rows and columns using eachcol and eachrow#

map a function over each column and return a vector

map(mean, eachcol(x))
10-element Vector{Float64}:
 0.5340356166118051
 0.581266221422634
 0.39863395825014675
 0.5913839384886548
 0.5349757146385773
 0.5474167357793596
 0.6097484043642387
 0.5739193910908156
 0.47936052129134554
 0.4337009355738717

an iteration returns a Pair with column name and values

foreach(c -> println(c[1], ": ", mean(c[2])), pairs(eachcol(x)))
x1: 0.5340356166118051
x2: 0.581266221422634
x3: 0.39863395825014675
x4: 0.5913839384886548
x5: 0.5349757146385773
x6: 0.5474167357793596
x7: 0.6097484043642387
x8: 0.5739193910908156
x9: 0.47936052129134554
x10: 0.4337009355738717

now the returned value is DataFrameRow which works as a NamedTuple but is a view to a parent DataFrame

map(r -> r.x1 / r.x2, eachrow(x))
10-element Vector{Float64}:
 0.28598028361408456
 0.8815489568706143
 1.211955077276455
 2.056076699409006
 1.3775932036047553
 0.23228344373783585
 7.860203109455978
 1.1260573845407145
 0.8312995463574625
 0.18491066455919594

it prints like a data frame, only the caption is different so that you know the type of the object

er = eachrow(x)
er.x1 ## you can access columns of a parent data frame directly
10-element Vector{Float64}:
 0.04977131658967582
 0.4690673288817153
 0.9607270015546927
 0.9543781600816001
 0.49045845644444097
 0.22669264058140504
 0.5205522834249062
 0.8811686488976916
 0.6159435670365279
 0.17159676262539625

it prints like a data frame, only the caption is different so that you know the type of the object

ec = eachcol(x)
10×10 DataFrameColumns
Rowx1x2x3x4x5x6x7x8x9x10
Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64
10.04977130.1740380.3356580.986170.8180460.3158020.1760870.886930.3314780.565418
20.4690670.5320940.5225630.6982940.6845670.7137360.2363390.4362620.4382890.501549
30.9607270.7927080.2195940.9918140.8530470.6613150.2278330.7966720.8305720.0412893
40.9543780.4641740.4694490.2071810.980270.8117470.9080940.1875830.1273470.11277
50.4904580.3560260.2200180.6729670.04627230.5789730.8383520.1452250.7189350.254138
60.2266930.9759310.824750.1329410.4861350.1893520.3053740.4785350.4571870.0475593
70.5205520.06622630.1543050.4401290.5082490.5319720.6040840.382340.6658010.563294
80.8811690.7825260.139470.5717470.2405820.5569180.9815250.8133370.079420.616259
90.6159440.7409410.1553280.4508760.7317920.4140140.9955690.8254180.8080660.795116
100.1715970.9279980.9452040.7617210.0007961490.7003390.8242260.7868920.336510.839618

you can access columns of a parent data frame directly

ec.x1
10-element Vector{Float64}:
 0.04977131658967582
 0.4690673288817153
 0.9607270015546927
 0.9543781600816001
 0.49045845644444097
 0.22669264058140504
 0.5205522834249062
 0.8811686488976916
 0.6159435670365279
 0.17159676262539625

Transposing#

you can transpose a data frame using permutedims:

df = DataFrame(reshape(1:12, 3, 4), :auto)
3×4 DataFrame
Rowx1x2x3x4
Int64Int64Int64Int64
114710
225811
336912
df.names = ["a", "b", "c"]
3-element Vector{String}:
 "a"
 "b"
 "c"
permutedims(df, :names)
4×4 DataFrame
Rownamesabc
StringInt64Int64Int64
1x1123
2x2456
3x3789
4x4101112

This notebook was generated using Literate.jl.