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.923554
2220.525914
3310.611834
4420.105175
5110.926859
6220.843111
7310.173183
8420.439764
groupby(x, :id)

GroupedDataFrame with 4 groups based on key: id

First Group (2 rows): id = 1
Rowidid2v
Int64Int64Float64
1110.923554
2110.926859

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

GroupedDataFrame with 1 group based on key:

First Group (8 rows):
Rowidid2v
Int64Int64Float64
1110.923554
2220.525914
3310.611834
4420.105175
5110.926859
6220.843111
7310.173183
8420.439764
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.923554
2110.926859

Last Group (2 rows): id = 4, id2 = 2
Rowidid2v
Int64Int64Float64
1420.105175
2420.439764

get the parent DataFrame

parent(gx2)
8×3 DataFrame
Rowidid2v
Int64Int64Float64
1110.923554
2220.525914
3310.611834
4420.105175
5110.926859
6220.843111
7310.173183
8420.439764

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

vcat(gx2...)
8×3 DataFrame
Rowidid2v
Int64Int64Float64
1110.923554
2110.926859
3220.525914
4220.843111
5310.611834
6310.173183
7420.105175
8420.439764

the same as above

DataFrame(gx2)
8×3 DataFrame
Rowidid2v
Int64Int64Float64
1110.923554
2110.926859
3220.525914
4220.843111
5310.611834
6310.173183
7420.105175
8420.439764

drop grouping columns when creating a data frame

DataFrame(gx2, keepkeys=false)
8×1 DataFrame
Rowv
Float64
10.923554
20.926859
30.525914
40.843111
50.611834
60.173183
70.105175
80.439764

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.923554
2110.926859

Last Group (2 rows): id = 4, id2 = 2
Rowidid2v
Int64Int64Float64
1420.105175
2420.439764
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.923554
   2 │     1      1  0.926859, 2×3 SubDataFrame
 Row  id     id2    v        
     │ Int64  Int64  Float64  
─────┼────────────────────────
   1 │     1      1  0.923554
   2 │     1      1  0.926859, 2×3 SubDataFrame
 Row  id     id2    v        
     │ Int64  Int64  Float64  
─────┼────────────────────────
   1 │     1      1  0.923554
   2 │     1      1  0.926859, 2×3 SubDataFrame
 Row  id     id2    v        
     │ Int64  Int64  Float64  
─────┼────────────────────────
   1 │     1      1  0.923554
   2 │     1      1  0.926859)

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
1a0.835577
2c0.281793
3a0.578997
4b0.0623499
5a0.627195
6d0.871266
7a0.0218157
8c0.404754
9d0.787053
10c0.498892
11b0.229484
12d0.315011
13a0.921946
89d0.067035
90a0.933599
91c0.849821
92c0.906701
93b0.736553
94b0.779055
95b0.985637
96a0.34354
97d0.935088
98c0.742881
99a0.932195
100a0.730541

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
1a0.585795
2c0.460639
3b0.528949
4d0.585117
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
1a0.83557710.585795
2c0.28179320.460639
3a0.57899730.585795
4b0.062349940.528949
5a0.62719550.585795
6d0.87126660.585117
7a0.021815770.585795
8c0.40475480.460639
9d0.78705390.585117
10c0.498892100.460639
11b0.229484110.528949
12d0.315011120.585117
13a0.921946130.585795
89d0.067035890.585117
90a0.933599900.585795
91c0.849821910.460639
92c0.906701920.460639
93b0.736553930.528949
94b0.779055940.528949
95b0.985637950.528949
96a0.34354960.585795
97d0.935088970.585117
98c0.742881980.460639
99a0.932195990.585795
100a0.7305411000.585795

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
1a10.585795
2a30.585795
3a50.585795
4a70.585795
5a130.585795
6a170.585795
7a190.585795
8a250.585795
9a260.585795
10a270.585795
11a280.585795
12a300.585795
13a370.585795
89d640.585117
90d650.585117
91d680.585117
92d710.585117
93d770.585117
94d780.585117
95d800.585117
96d850.585117
97d870.585117
98d880.585117
99d890.585117
100d970.585117

we give a custom name for the result column

@chain x begin
    groupby(:id)
    combine(:v => mean => :res)
end
4×2 DataFrame
Rowidres
CharFloat64
1a0.585795
2c0.460639
3b0.528949
4d0.585117

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
1a0.58579516.402328
2c0.4606398.2914918
3b0.52894911.636922
4d0.58511718.723732

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
2×2 DataFrame
Rowidn
CharInt64
1a28
2d32

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.8882220.08096050.4034290.5116080.9658160.4788980.3718560.9579150.1293780.876398
20.9693580.02178660.9018860.4103780.8129170.2551340.910580.00885010.8881410.743186
30.03501180.2771280.6725710.9110960.9726570.7837270.2983560.1874140.5551250.681353
40.312990.1412340.09834230.5909390.06825730.3844610.9986030.7041680.2001360.379971
50.2568350.4587440.849230.4705790.5253860.1287360.6960990.1921210.7346840.397709
60.6752310.2266360.112040.0468390.7439860.4151680.3260530.6125820.7082170.456039
70.4096240.7199650.6937780.7139990.2558680.9410090.4601040.1370390.04508710.426524
80.3617760.08729050.7550170.978360.6585330.3767030.3213280.06356760.3177170.130425
90.5022910.094310.8075590.564330.5880480.04126320.7317460.1585570.3781160.406653
100.02382440.2221550.8448150.4885890.746490.4118050.2622410.3525720.01192430.1269
mapcols(mean, x)
1×10 DataFrame
Rowx1x2x3x4x5x6x7x8x9x10
Float64Float64Float64Float64Float64Float64Float64Float64Float64Float64
10.4435160.2330210.6138670.5686720.6337960.421690.5376960.3374790.3968530.462516

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.44351626991809645
 0.23302107000340802
 0.6138666895806199
 0.5686716035619371
 0.633795739464339
 0.4216904417231671
 0.5376964271412635
 0.33747865010160033
 0.3968525913053566
 0.4625157129085385

an iteration returns a Pair with column name and values

foreach(c -> println(c[1], ": ", mean(c[2])), pairs(eachcol(x)))
x1: 0.44351626991809645
x2: 0.23302107000340802
x3: 0.6138666895806199
x4: 0.5686716035619371
x5: 0.633795739464339
x6: 0.4216904417231671
x7: 0.5376964271412635
x8: 0.33747865010160033
x9: 0.3968525913053566
x10: 0.4625157129085385

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}:
 10.971054379628248
 44.49338049460191
  0.1263380337364685
  2.2161041599136193
  0.5598644975669603
  2.9793662606153277
  0.5689497869814226
  4.144501187588225
  5.325959217502414
  0.10724220030834118

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.8882216562522717
 0.9693580655050634
 0.03501184143705083
 0.31299002717386293
 0.2568346884017747
 0.6752310702251116
 0.40962414133358827
 0.36177556410656886
 0.5022912541860961
 0.02382439055957608

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.8882220.08096050.4034290.5116080.9658160.4788980.3718560.9579150.1293780.876398
20.9693580.02178660.9018860.4103780.8129170.2551340.910580.00885010.8881410.743186
30.03501180.2771280.6725710.9110960.9726570.7837270.2983560.1874140.5551250.681353
40.312990.1412340.09834230.5909390.06825730.3844610.9986030.7041680.2001360.379971
50.2568350.4587440.849230.4705790.5253860.1287360.6960990.1921210.7346840.397709
60.6752310.2266360.112040.0468390.7439860.4151680.3260530.6125820.7082170.456039
70.4096240.7199650.6937780.7139990.2558680.9410090.4601040.1370390.04508710.426524
80.3617760.08729050.7550170.978360.6585330.3767030.3213280.06356760.3177170.130425
90.5022910.094310.8075590.564330.5880480.04126320.7317460.1585570.3781160.406653
100.02382440.2221550.8448150.4885890.746490.4118050.2622410.3525720.01192430.1269

you can access columns of a parent data frame directly

ec.x1
10-element Vector{Float64}:
 0.8882216562522717
 0.9693580655050634
 0.03501184143705083
 0.31299002717386293
 0.2568346884017747
 0.6752310702251116
 0.40962414133358827
 0.36177556410656886
 0.5022912541860961
 0.02382439055957608

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.