forked from JuliaData/DataFrames.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomposer.jl
1352 lines (1195 loc) · 58 KB
/
composer.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##
## Join / merge
##
# Like similar, but returns a array that can have missings and is initialized with missings
similar_missing(dv::AbstractArray{T}, dims::Union{Int, Tuple{Vararg{Int}}}) where {T} =
fill!(similar(dv, Union{T, Missing}, dims), missing)
similar_outer(leftcol::AbstractVector, rightcol::AbstractVector, n::Int) =
Tables.allocatecolumn(promote_type(eltype(leftcol), eltype(rightcol)), n)
const OnType = Union{SymbolOrString, NTuple{2, Symbol}, Pair{Symbol, Symbol},
Pair{<:AbstractString, <:AbstractString}}
# helper structure for DataFrames joining
struct DataFrameJoiner
dfl::AbstractDataFrame
dfr::AbstractDataFrame
dfl_on::AbstractDataFrame
dfr_on::AbstractDataFrame
left_on::Vector{Symbol}
right_on::Vector{Symbol}
function DataFrameJoiner(dfl::AbstractDataFrame, dfr::AbstractDataFrame,
on::Union{<:OnType, AbstractVector},
matchmissing::Symbol,
kind::Symbol)
on_cols = isa(on, AbstractVector) ? on : [on]
left_on = Symbol[]
right_on = Symbol[]
for v in on_cols
if v isa SymbolOrString
push!(left_on, Symbol(v))
push!(right_on, Symbol(v))
elseif v isa Union{Pair{Symbol, Symbol},
Pair{<:AbstractString, <:AbstractString}}
push!(left_on, Symbol(first(v)))
push!(right_on, Symbol(last(v)))
elseif v isa NTuple{2, Symbol}
# an explicit error is thrown as Tuple{Symbol, Symbol} was supported in the past
throw(ArgumentError("Using a `Tuple{Symbol, Symbol}` or a vector containing " *
"such tuples as a value of `on` keyword argument is " *
"not supported: use `Pair{Symbol, Symbol}` instead."))
else
throw(ArgumentError("All elements of `on` argument to `join` must be " *
"Symbol or Pair{Symbol, Symbol}."))
end
end
if matchmissing === :notequal
if kind in (:left, :semi, :anti)
dfr = dropmissing(dfr, right_on, view=true)
elseif kind === :right
dfl = dropmissing(dfl, left_on, view=true)
elseif kind === :inner
# it possible to drop only left or right df
# to gain some performance but needs more testing, see #2724
dfl = dropmissing(dfl, left_on, view=true)
dfr = dropmissing(dfr, right_on, view=true)
elseif kind === :outer
throw(ArgumentError("matchmissing == :notequal for `outerjoin` is not allowed"))
else
throw(ArgumentError("matchmissing == :notequal not implemented for kind == :$kind"))
end
end
dfl_on = select(dfl, left_on, copycols=false)
dfr_on = select(dfr, right_on, copycols=false)
if matchmissing === :error
for df in (dfl_on, dfr_on), col in eachcol(df)
if any(ismissing, col)
throw(ArgumentError("missing values in key columns are not allowed " *
"when matchmissing == :error"))
end
end
elseif !(matchmissing in (:equal, :notequal))
throw(ArgumentError("matchmissing allows only :error, :equal, or :notequal"))
end
for df in (dfl_on, dfr_on), col in eachcol(df)
if any(x -> (x isa Union{Complex, Real}) &&
(isnan(x) || isequal(real(x), -0.0) || isequal(imag(x), -0.0)), col)
throw(ArgumentError("currently for numeric values NaN and `-0.0` " *
"in their real or imaginary components are not " *
"allowed. Use CategoricalArrays.jl to wrap " *
"these values in a CategoricalVector to perform " *
"the requested join."))
end
end
new(dfl, dfr, dfl_on, dfr_on, left_on, right_on)
end
end
# helper map between the row indices in original and joined table
struct RowIndexMap
"row indices in the original table"
orig::Vector{Int}
"row indices in the resulting joined table"
join::Vector{Int}
end
Base.length(x::RowIndexMap) = length(x.orig)
_rename_cols(old_names::AbstractVector{Symbol},
renamecols::Union{Function, Symbol, AbstractString},
exclude::AbstractVector{Symbol} = Symbol[]) =
Symbol[n in exclude ? n :
(renamecols isa Function ? Symbol(renamecols(string(n))) : Symbol(n, renamecols))
for n in old_names]
function compose_inner_table(joiner::DataFrameJoiner,
makeunique::Bool,
left_rename::Union{Function, AbstractString, Symbol},
right_rename::Union{Function, AbstractString, Symbol})
left_ixs, right_ixs = find_inner_rows(joiner)
@static if VERSION >= v"1.4"
if Threads.nthreads() > 1 && length(left_ixs) >= 1_000_000
dfl_task = Threads.@spawn joiner.dfl[left_ixs, :]
dfr_noon_task = Threads.@spawn joiner.dfr[right_ixs, Not(joiner.right_on)]
dfl = fetch(dfl_task)
dfr_noon = fetch(dfr_noon_task)
else
dfl = joiner.dfl[left_ixs, :]
dfr_noon = joiner.dfr[right_ixs, Not(joiner.right_on)]
end
else
dfl = joiner.dfl[left_ixs, :]
dfr_noon = joiner.dfr[right_ixs, Not(joiner.right_on)]
end
ncleft = ncol(dfl)
cols = Vector{AbstractVector}(undef, ncleft + ncol(dfr_noon))
for (i, col) in enumerate(eachcol(dfl))
cols[i] = col
end
for (i, col) in enumerate(eachcol(dfr_noon))
cols[i+ncleft] = col
end
new_names = vcat(_rename_cols(_names(joiner.dfl), left_rename, joiner.left_on),
_rename_cols(_names(dfr_noon), right_rename))
res = DataFrame(cols, new_names, makeunique=makeunique, copycols=false)
return res
end
function find_missing_idxs(present::Vector{Int}, target_len::Int)
not_seen = trues(target_len)
@inbounds for v in present
not_seen[v] = false
end
return _findall(not_seen)
end
function compose_joined_table(joiner::DataFrameJoiner, kind::Symbol, makeunique::Bool,
left_rename::Union{Function, AbstractString, Symbol},
right_rename::Union{Function, AbstractString, Symbol},
indicator::Union{Nothing, Symbol, AbstractString})
@assert kind == :left || kind == :right || kind == :outer
left_ixs, right_ixs = find_inner_rows(joiner)
if kind == :left || kind == :outer
leftonly_ixs = find_missing_idxs(left_ixs, nrow(joiner.dfl))
else
leftonly_ixs = 1:0
end
if kind == :right || kind == :outer
rightonly_ixs = find_missing_idxs(right_ixs, nrow(joiner.dfr))
else
rightonly_ixs = 1:0
end
return _compose_joined_table(joiner, kind, makeunique, left_rename, right_rename,
indicator, left_ixs, right_ixs, leftonly_ixs, rightonly_ixs)
end
function _compose_joined_table(joiner::DataFrameJoiner, kind::Symbol, makeunique::Bool,
left_rename::Union{Function, AbstractString, Symbol},
right_rename::Union{Function, AbstractString, Symbol},
indicator::Union{Nothing, Symbol, AbstractString},
left_ixs::AbstractVector, right_ixs::AbstractVector,
leftonly_ixs::AbstractVector, rightonly_ixs::AbstractVector)
lil = length(left_ixs)
ril = length(right_ixs)
loil = length(leftonly_ixs)
roil = length(rightonly_ixs)
@assert lil == ril
dfl_noon = select(joiner.dfl, Not(joiner.left_on), copycols=false)
dfr_noon = select(joiner.dfr, Not(joiner.right_on), copycols=false)
target_nrow = lil + loil + roil
_similar_left = kind == :left ? similar : similar_missing
_similar_right = kind == :right ? similar : similar_missing
if isnothing(indicator)
src_indicator = nothing
else
src_indicator = Vector{UInt32}(undef, target_nrow)
src_indicator[1:lil] .= 3
src_indicator[lil + 1:lil + loil] .= 1
src_indicator[lil + loil + 1:target_nrow] .= 2
end
cols = Vector{AbstractVector}(undef, ncol(joiner.dfl) + ncol(dfr_noon))
col_idx = 1
left_idxs = [columnindex(joiner.dfl, n) for n in joiner.left_on]
append!(left_idxs, setdiff(1:ncol(joiner.dfl), left_idxs))
if kind == :left
@assert loil + lil == target_nrow
for col in eachcol(joiner.dfl_on)
cols_i = left_idxs[col_idx]
cols[cols_i] = similar(col, target_nrow)
copyto!(cols[cols_i], view(col, left_ixs))
copyto!(cols[cols_i], lil + 1, view(col, leftonly_ixs), 1, loil)
col_idx += 1
end
elseif kind == :right
@assert roil + ril == target_nrow
for col in eachcol(joiner.dfr_on)
cols_i = left_idxs[col_idx]
cols[cols_i] = similar(col, target_nrow)
copyto!(cols[cols_i], view(col, right_ixs))
copyto!(cols[cols_i], lil + 1, view(col, rightonly_ixs), 1, roil)
col_idx += 1
end
else
@assert kind == :outer
@assert loil + roil + ril == target_nrow
for (lcol, rcol) in zip(eachcol(joiner.dfl_on), eachcol(joiner.dfr_on))
cols_i = left_idxs[col_idx]
cols[cols_i] = similar_outer(lcol, rcol, target_nrow)
copyto!(cols[cols_i], view(lcol, left_ixs))
copyto!(cols[cols_i], lil + 1, view(lcol, leftonly_ixs), 1, loil)
copyto!(cols[cols_i], lil + loil + 1, view(rcol, rightonly_ixs), 1, roil)
col_idx += 1
end
end
@assert col_idx == ncol(joiner.dfl_on) + 1
@static if VERSION >= v"1.4"
if Threads.nthreads() > 1 && target_nrow >= 1_000_000 && length(cols) > col_idx
@sync begin
for col in eachcol(dfl_noon)
cols_i = left_idxs[col_idx]
Threads.@spawn _noon_compose_helper!(cols, _similar_left, cols_i,
col, target_nrow, left_ixs, lil + 1, leftonly_ixs, loil)
col_idx += 1
end
@assert col_idx == ncol(joiner.dfl) + 1
for col in eachcol(dfr_noon)
cols_i = col_idx
Threads.@spawn _noon_compose_helper!(cols, _similar_right, cols_i, col, target_nrow,
right_ixs, lil + loil + 1, rightonly_ixs, roil)
col_idx += 1
end
end
else
for col in eachcol(dfl_noon)
_noon_compose_helper!(cols, _similar_left, left_idxs[col_idx],
col, target_nrow, left_ixs, lil + 1, leftonly_ixs, loil)
col_idx += 1
end
@assert col_idx == ncol(joiner.dfl) + 1
for col in eachcol(dfr_noon)
_noon_compose_helper!(cols, _similar_right, col_idx, col, target_nrow,
right_ixs, lil + loil + 1, rightonly_ixs, roil)
col_idx += 1
end
end
else
for col in eachcol(dfl_noon)
_noon_compose_helper!(cols, _similar_left, left_idxs[col_idx],
col, target_nrow, left_ixs, lil + 1, leftonly_ixs, loil)
col_idx += 1
end
@assert col_idx == ncol(joiner.dfl) + 1
for col in eachcol(dfr_noon)
_noon_compose_helper!(cols, _similar_right, col_idx, col, target_nrow,
right_ixs, lil + loil + 1, rightonly_ixs, roil)
col_idx += 1
end
end
@assert col_idx == length(cols) + 1
new_names = vcat(_rename_cols(_names(joiner.dfl), left_rename, joiner.left_on),
_rename_cols(_names(dfr_noon), right_rename))
res = DataFrame(cols, new_names, makeunique=makeunique, copycols=false)
return res, src_indicator
end
function _noon_compose_helper!(cols::Vector{AbstractVector}, # target container to populate
similar_col::Function, # function to use to materialize new column
cols_i::Integer, # index in cols to populate
col::AbstractVector, # source column
target_nrow::Integer, # target number of rows in new column
side_ixs::AbstractVector, # indices in col that were matched
offset::Integer, # offset to put non matched indices
sideonly_ixs::AbstractVector, # indices in col that were not
tocopy::Integer) # number on non-matched rows to copy
@assert tocopy == length(sideonly_ixs)
cols[cols_i] = similar_col(col, target_nrow)
copyto!(cols[cols_i], view(col, side_ixs))
copyto!(cols[cols_i], offset, view(col, sideonly_ixs), 1, tocopy)
end
function _join(df1::AbstractDataFrame, df2::AbstractDataFrame;
on::Union{<:OnType, AbstractVector}, kind::Symbol, makeunique::Bool,
indicator::Union{Nothing, Symbol, AbstractString},
validate::Union{Pair{Bool, Bool}, Tuple{Bool, Bool}},
left_rename::Union{Function, AbstractString, Symbol},
right_rename::Union{Function, AbstractString, Symbol},
matchmissing::Symbol)
_check_consistency(df1)
_check_consistency(df2)
if on == []
throw(ArgumentError("Missing join argument 'on'."))
end
joiner = DataFrameJoiner(df1, df2, on, matchmissing, kind)
# Check merge key validity
left_invalid = validate[1] ? any(nonunique(joiner.dfl, joiner.left_on)) : false
right_invalid = validate[2] ? any(nonunique(joiner.dfr, joiner.right_on)) : false
if validate[1]
non_unique_left = nonunique(joiner.dfl, joiner.left_on)
if any(non_unique_left)
left_invalid = true
non_unique_left_df = unique(joiner.dfl[non_unique_left, joiner.left_on])
nrow_nul_df = nrow(non_unique_left_df)
@assert nrow_nul_df > 0
if nrow_nul_df == 1
left_invalid_msg = "df1 contains 1 duplicate key: " *
"$(NamedTuple(non_unique_left_df[1, :])). "
elseif nrow_nul_df == 2
left_invalid_msg = "df1 contains 2 duplicate keys: " *
"$(NamedTuple(non_unique_left_df[1, :])) and " *
"$(NamedTuple(non_unique_left_df[2, :])). "
else
left_invalid_msg = "df1 contains $(nrow_nul_df) duplicate keys: " *
"$(NamedTuple(non_unique_left_df[1, :])), ..., " *
"$(NamedTuple(non_unique_left_df[end, :])). "
end
else
left_invalid = false
left_invalid_msg = ""
end
else
left_invalid = false
left_invalid_msg = ""
end
if validate[2]
non_unique_right = nonunique(joiner.dfr, joiner.right_on)
if any(non_unique_right)
right_invalid = true
non_unique_right_df = unique(joiner.dfr[non_unique_right, joiner.right_on])
nrow_nur_df = nrow(non_unique_right_df)
@assert nrow_nur_df > 0
if nrow_nur_df == 1
right_invalid_msg = "df2 contains 1 duplicate key: " *
"$(NamedTuple(non_unique_right_df[1, :]))."
elseif nrow_nur_df == 2
right_invalid_msg = "df2 contains 2 duplicate keys: " *
"$(NamedTuple(non_unique_right_df[1, :])) and " *
"$(NamedTuple(non_unique_right_df[2, :]))."
else
right_invalid_msg = "df2 contains $(nrow_nur_df) duplicate keys: " *
"$(NamedTuple(non_unique_right_df[1, :])), ..., " *
"$(NamedTuple(non_unique_right_df[end, :]))."
end
else
right_invalid = false
right_invalid_msg = ""
end
else
right_invalid = false
right_invalid_msg = ""
end
if left_invalid && right_invalid
first_error_df1 = findfirst(nonunique(joiner.dfl, joiner.left_on))
first_error_df2 = findfirst(nonunique(joiner.dfr, joiner.right_on))
throw(ArgumentError("Merge key(s) are not unique in both df1 and df2. " *
left_invalid_msg * right_invalid_msg))
elseif left_invalid
first_error = findfirst(nonunique(joiner.dfl, joiner.left_on))
throw(ArgumentError("Merge key(s) in df1 are not unique. " *
left_invalid_msg))
elseif right_invalid
first_error = findfirst(nonunique(joiner.dfr, joiner.right_on))
throw(ArgumentError("Merge key(s) in df2 are not unique. " *
right_invalid_msg))
end
src_indicator = nothing
if kind == :inner
joined = compose_inner_table(joiner, makeunique, left_rename, right_rename)
elseif kind == :left
joined, src_indicator =
compose_joined_table(joiner, kind, makeunique, left_rename, right_rename, indicator)
elseif kind == :right
joined, src_indicator =
compose_joined_table(joiner, kind, makeunique, left_rename, right_rename, indicator)
elseif kind == :outer
joined, src_indicator =
compose_joined_table(joiner, kind, makeunique, left_rename, right_rename, indicator)
elseif kind == :semi
joined = joiner.dfl[find_semi_rows(joiner), :]
elseif kind == :anti
joined = joiner.dfl[.!find_semi_rows(joiner), :]
else
throw(ArgumentError("Unknown kind of join requested: $kind"))
end
if indicator !== nothing
pool = ["left_only", "right_only", "both"]
invpool = Dict{String, UInt32}("left_only" => 1,
"right_only" => 2,
"both" => 3)
indicatorcol = PooledArray(PooledArrays.RefArray(src_indicator),
invpool, pool)
unique_indicator = indicator
if makeunique
try_idx = 0
while hasproperty(joined, unique_indicator)
try_idx += 1
unique_indicator = Symbol(string(indicator, "_", try_idx))
end
end
if hasproperty(joined, unique_indicator)
throw(ArgumentError("joined data frame already has column " *
":$unique_indicator. Pass makeunique=true to " *
"make it unique using a suffix automatically."))
end
joined[!, unique_indicator] = indicatorcol
else
@assert isnothing(src_indicator)
end
return joined
end
"""
innerjoin(df1, df2; on, makeunique=false, validate=(false, false),
renamecols=(identity => identity), matchmissing=:error)
innerjoin(df1, df2, dfs...; on, makeunique=false,
validate=(false, false), matchmissing=:error)
Perform an inner join of two or more data frame objects and return a `DataFrame`
containing the result. An inner join includes rows with keys that match in all
passed data frames.
The order of rows in the result is undefined and may change in the future releases.
In the returned data frame the type of the columns on which the data frames are
joined is determined by the type of these columns in `df1`. This behavior may
change in future releases.
# Arguments
- `df1`, `df2`, `dfs...`: the `AbstractDataFrames` to be joined
# Keyword Arguments
- `on` : A column name to join `df1` and `df2` on. If the columns on which
`df1` and `df2` will be joined have different names, then a `left=>right`
pair can be passed. It is also allowed to perform a join on multiple columns,
in which case a vector of column names or column name pairs can be passed
(mixing names and pairs is allowed). If more than two data frames are joined
then only a column name or a vector of column names are allowed.
`on` is a required argument.
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found in columns not joined on;
if `true`, duplicate names will be suffixed with `_i`
(`i` starting at 1 for the first duplicate).
- `validate` : whether to check that columns passed as the `on` argument
define unique keys in each input data frame (according to `isequal`).
Can be a tuple or a pair, with the first element indicating whether to
run check for `df1` and the second element for `df2`.
By default no check is performed.
- `renamecols` : a `Pair` specifying how columns of left and right data frames should
be renamed in the resulting data frame. Each element of the pair can be a
string or a `Symbol` can be passed in which case it is appended to the original
column name; alternatively a function can be passed in which case it is applied
to each column name, which is passed to it as a `String`. Note that `renamecols`
does not affect `on` columns, whose names are always taken from the left
data frame and left unchanged.
- `matchmissing` : if equal to `:error` throw an error if `missing` is present
in `on` columns; if equal to `:equal` then `missing` is allowed and missings are
matched; if equal to `:notequal` then missings are dropped in `df1` and `df2`
`on` columns; `isequal` is used for comparisons of rows for equality
It is not allowed to join on columns that contain `NaN` or `-0.0` in real or
imaginary part of the number. If you need to perform a join on such values use
CategoricalArrays.jl and transform a column containing such values into a
`CategoricalVector`.
When merging `on` categorical columns that differ in the ordering of their
levels, the ordering of the left data frame takes precedence over the ordering
of the right data frame.
If more than two data frames are passed, the join is performed recursively with
left associativity. In this case the `validate` keyword argument is applied
recursively with left associativity.
See also: [`leftjoin`](@ref), [`rightjoin`](@ref), [`outerjoin`](@ref),
[`semijoin`](@ref), [`antijoin`](@ref), [`crossjoin`](@ref).
# Examples
```jldoctest
julia> name = DataFrame(ID = [1, 2, 3], Name = ["John Doe", "Jane Doe", "Joe Blogs"])
3×2 DataFrame
Row │ ID Name
│ Int64 String
─────┼──────────────────
1 │ 1 John Doe
2 │ 2 Jane Doe
3 │ 3 Joe Blogs
julia> job = DataFrame(ID = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ ID Job
│ Int64 String
─────┼───────────────
1 │ 1 Lawyer
2 │ 2 Doctor
3 │ 4 Farmer
julia> innerjoin(name, job, on = :ID)
2×3 DataFrame
Row │ ID Name Job
│ Int64 String String
─────┼─────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
julia> job2 = DataFrame(identifier = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ identifier Job
│ Int64 String
─────┼────────────────────
1 │ 1 Lawyer
2 │ 2 Doctor
3 │ 4 Farmer
julia> innerjoin(name, job2, on = :ID => :identifier, renamecols = "_left" => "_right")
2×3 DataFrame
Row │ ID Name_left Job_right
│ Int64 String String
─────┼─────────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
julia> innerjoin(name, job2, on = [:ID => :identifier], renamecols = uppercase => lowercase)
2×3 DataFrame
Row │ ID NAME job
│ Int64 String String
─────┼─────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
```
"""
function innerjoin(df1::AbstractDataFrame, df2::AbstractDataFrame;
on::Union{<:OnType, AbstractVector} = Symbol[],
makeunique::Bool=false,
validate::Union{Pair{Bool, Bool}, Tuple{Bool, Bool}}=(false, false),
renamecols::Pair=identity => identity,
matchmissing::Symbol=:error)
if !all(x -> x isa Union{Function, AbstractString, Symbol}, renamecols)
throw(ArgumentError("renamecols keyword argument must be a `Pair` " *
"containing functions, strings, or `Symbol`s"))
end
return _join(df1, df2, on=on, kind=:inner, makeunique=makeunique,
indicator=nothing, validate=validate,
left_rename=first(renamecols), right_rename=last(renamecols),
matchmissing=matchmissing)
end
innerjoin(df1::AbstractDataFrame, df2::AbstractDataFrame, dfs::AbstractDataFrame...;
on::Union{<:OnType, AbstractVector} = Symbol[],
makeunique::Bool=false,
validate::Union{Pair{Bool, Bool}, Tuple{Bool, Bool}}=(false, false),
matchmissing::Symbol=:error) =
innerjoin(innerjoin(df1, df2, on=on, makeunique=makeunique, validate=validate),
dfs..., on=on, makeunique=makeunique, validate=validate,
matchmissing=matchmissing)
"""
leftjoin(df1, df2; on, makeunique=false, source=nothing, validate=(false, false),
renamecols=(identity => identity), matchmissing=:error)
Perform a left join of two data frame objects and return a `DataFrame` containing
the result. A left join includes all rows from `df1`.
The order of rows in the result is undefined and may change in the future releases.
In the returned data frame the type of the columns on which the data frames are
joined is determined by the type of these columns in `df1`. This behavior may
change in future releases.
# Arguments
- `df1`, `df2`: the `AbstractDataFrames` to be joined
# Keyword Arguments
- `on` : A column name to join `df1` and `df2` on. If the columns on which
`df1` and `df2` will be joined have different names, then a `left=>right`
pair can be passed. It is also allowed to perform a join on multiple columns,
in which case a vector of column names or column name pairs can be passed
(mixing names and pairs is allowed).
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found in columns not joined on;
if `true`, duplicate names will be suffixed with `_i`
(`i` starting at 1 for the first duplicate).
- `source` : Default: `nothing`. If a `Symbol` or string, adds indicator
column with the given name, for whether a row appeared in only `df1` (`"left_only"`),
only `df2` (`"right_only"`) or in both (`"both"`). If the name is already in use,
the column name will be modified if `makeunique=true`.
- `validate` : whether to check that columns passed as the `on` argument
define unique keys in each input data frame (according to `isequal`).
Can be a tuple or a pair, with the first element indicating whether to
run check for `df1` and the second element for `df2`.
By default no check is performed.
- `renamecols` : a `Pair` specifying how columns of left and right data frames should
be renamed in the resulting data frame. Each element of the pair can be a
string or a `Symbol` can be passed in which case it is appended to the original
column name; alternatively a function can be passed in which case it is applied
to each column name, which is passed to it as a `String`. Note that `renamecols`
does not affect `on` columns, whose names are always taken from the left
data frame and left unchanged.
- `matchmissing` : if equal to `:error` throw an error if `missing` is present
in `on` columns; if equal to `:equal` then `missing` is allowed and missings are
matched; if equal to `:notequal` then missings are dropped in `df2` `on` columns;
`isequal` is used for comparisons of rows for equality
All columns of the returned data table will support missing values.
It is not allowed to join on columns that contain `NaN` or `-0.0` in real or
imaginary part of the number. If you need to perform a join on such values use
CategoricalArrays.jl and transform a column containing such values into a
`CategoricalVector`.
When merging `on` categorical columns that differ in the ordering of their
levels, the ordering of the left data frame takes precedence over the ordering
of the right data frame.
See also: [`innerjoin`](@ref), [`rightjoin`](@ref), [`outerjoin`](@ref),
[`semijoin`](@ref), [`antijoin`](@ref), [`crossjoin`](@ref).
# Examples
```jldoctest
julia> name = DataFrame(ID = [1, 2, 3], Name = ["John Doe", "Jane Doe", "Joe Blogs"])
3×2 DataFrame
Row │ ID Name
│ Int64 String
─────┼──────────────────
1 │ 1 John Doe
2 │ 2 Jane Doe
3 │ 3 Joe Blogs
julia> job = DataFrame(ID = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ ID Job
│ Int64 String
─────┼───────────────
1 │ 1 Lawyer
2 │ 2 Doctor
3 │ 4 Farmer
julia> leftjoin(name, job, on = :ID)
3×3 DataFrame
Row │ ID Name Job
│ Int64 String String?
─────┼───────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
3 │ 3 Joe Blogs missing
julia> job2 = DataFrame(identifier = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ identifier Job
│ Int64 String
─────┼────────────────────
1 │ 1 Lawyer
2 │ 2 Doctor
3 │ 4 Farmer
julia> leftjoin(name, job2, on = :ID => :identifier, renamecols = "_left" => "_right")
3×3 DataFrame
Row │ ID Name_left Job_right
│ Int64 String String?
─────┼─────────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
3 │ 3 Joe Blogs missing
julia> leftjoin(name, job2, on = [:ID => :identifier], renamecols = uppercase => lowercase)
3×3 DataFrame
Row │ ID NAME job
│ Int64 String String?
─────┼───────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
3 │ 3 Joe Blogs missing
```
"""
function leftjoin(df1::AbstractDataFrame, df2::AbstractDataFrame;
on::Union{<:OnType, AbstractVector} = Symbol[], makeunique::Bool=false,
source::Union{Nothing, Symbol, AbstractString}=nothing,
indicator::Union{Nothing, Symbol, AbstractString}=nothing,
validate::Union{Pair{Bool, Bool}, Tuple{Bool, Bool}}=(false, false),
renamecols::Pair=identity => identity, matchmissing::Symbol=:error)
if !all(x -> x isa Union{Function, AbstractString, Symbol}, renamecols)
throw(ArgumentError("renamecols keyword argument must be a `Pair` " *
"containing functions, strings, or `Symbol`s"))
end
if source === nothing
if indicator !== nothing
source = indicator
Base.depwarn("`indicator` keyword argument is deprecated and " *
"will be removed in 2.0 release of DataFrames.jl. " *
"Use `source` keyword argument instead.", :leftjoin)
end
elseif indicator !== nothing
throw(ArgumentError("`indicator` keyword argument is deprecated. " *
"It is not allowed to pass both `indicator` and `source` " *
"keyword arguments at the same time."))
end
return _join(df1, df2, on=on, kind=:left, makeunique=makeunique,
indicator=source, validate=validate,
left_rename=first(renamecols), right_rename=last(renamecols),
matchmissing=matchmissing)
end
"""
rightjoin(df1, df2; on, makeunique=false, source=nothing,
validate=(false, false), renamecols=(identity => identity),
matchmissing=:error)
Perform a right join on two data frame objects and return a `DataFrame` containing
the result. A right join includes all rows from `df2`.
The order of rows in the result is undefined and may change in the future releases.
In the returned data frame the type of the columns on which the data frames are
joined is determined by the type of these columns in `df2`. This behavior may
change in future releases.
# Arguments
- `df1`, `df2`: the `AbstractDataFrames` to be joined
# Keyword Arguments
- `on` : A column name to join `df1` and `df2` on. If the columns on which
`df1` and `df2` will be joined have different names, then a `left=>right`
pair can be passed. It is also allowed to perform a join on multiple columns,
in which case a vector of column names or column name pairs can be passed
(mixing names and pairs is allowed).
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found in columns not joined on;
if `true`, duplicate names will be suffixed with `_i`
(`i` starting at 1 for the first duplicate).
- `source` : Default: `nothing`. If a `Symbol` or string, adds indicator
column with the given name for whether a row appeared in only `df1` (`"left_only"`),
only `df2` (`"right_only"`) or in both (`"both"`). If the name is already in use,
the column name will be modified if `makeunique=true`.
- `validate` : whether to check that columns passed as the `on` argument
define unique keys in each input data frame (according to `isequal`).
Can be a tuple or a pair, with the first element indicating whether to
run check for `df1` and the second element for `df2`.
By default no check is performed.
- `renamecols` : a `Pair` specifying how columns of left and right data frames should
be renamed in the resulting data frame. Each element of the pair can be a
string or a `Symbol` can be passed in which case it is appended to the original
column name; alternatively a function can be passed in which case it is applied
to each column name, which is passed to it as a `String`. Note that `renamecols`
does not affect `on` columns, whose names are always taken from the left
data frame and left unchanged.
- `matchmissing` : if equal to `:error` throw an error if `missing` is present
in `on` columns; if equal to `:equal` then `missing` is allowed and missings are
matched; if equal to `:notequal` then missings are dropped in `df1` `on` columns;
`isequal` is used for comparisons of rows for equality
All columns of the returned data table will support missing values.
It is not allowed to join on columns that contain `NaN` or `-0.0` in real or
imaginary part of the number. If you need to perform a join on such values use
CategoricalArrays.jl and transform a column containing such values into a
`CategoricalVector`.
When merging `on` categorical columns that differ in the ordering of their
levels, the ordering of the left data frame takes precedence over the ordering
of the right data frame.
See also: [`innerjoin`](@ref), [`leftjoin`](@ref), [`outerjoin`](@ref),
[`semijoin`](@ref), [`antijoin`](@ref), [`crossjoin`](@ref).
# Examples
```jldoctest
julia> name = DataFrame(ID = [1, 2, 3], Name = ["John Doe", "Jane Doe", "Joe Blogs"])
3×2 DataFrame
Row │ ID Name
│ Int64 String
─────┼──────────────────
1 │ 1 John Doe
2 │ 2 Jane Doe
3 │ 3 Joe Blogs
julia> job = DataFrame(ID = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ ID Job
│ Int64 String
─────┼───────────────
1 │ 1 Lawyer
2 │ 2 Doctor
3 │ 4 Farmer
julia> rightjoin(name, job, on = :ID)
3×3 DataFrame
Row │ ID Name Job
│ Int64 String? String
─────┼─────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
3 │ 4 missing Farmer
julia> job2 = DataFrame(identifier = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ identifier Job
│ Int64 String
─────┼────────────────────
1 │ 1 Lawyer
2 │ 2 Doctor
3 │ 4 Farmer
julia> rightjoin(name, job2, on = :ID => :identifier, renamecols = "_left" => "_right")
3×3 DataFrame
Row │ ID Name_left Job_right
│ Int64 String? String
─────┼─────────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
3 │ 4 missing Farmer
julia> rightjoin(name, job2, on = [:ID => :identifier], renamecols = uppercase => lowercase)
3×3 DataFrame
Row │ ID NAME job
│ Int64 String? String
─────┼─────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
3 │ 4 missing Farmer
```
"""
function rightjoin(df1::AbstractDataFrame, df2::AbstractDataFrame;
on::Union{<:OnType, AbstractVector} = Symbol[], makeunique::Bool=false,
source::Union{Nothing, Symbol, AbstractString}=nothing,
indicator::Union{Nothing, Symbol, AbstractString}=nothing,
validate::Union{Pair{Bool, Bool}, Tuple{Bool, Bool}}=(false, false),
renamecols::Pair=identity => identity, matchmissing::Symbol=:error)
if !all(x -> x isa Union{Function, AbstractString, Symbol}, renamecols)
throw(ArgumentError("renamecols keyword argument must be a `Pair` " *
"containing functions, strings, or `Symbol`s"))
end
if source === nothing
if indicator !== nothing
source = indicator
Base.depwarn("`indicator` keyword argument is deprecated and " *
"will be removed in 2.0 release of DataFrames.jl. " *
"Use `source` keyword argument instead.", :rightjoin)
end
elseif indicator !== nothing
throw(ArgumentError("`indicator` keyword argument is deprecated. " *
"It is not allowed to pass both `indicator` and `source` " *
"keyword arguments at the same time."))
end
return _join(df1, df2, on=on, kind=:right, makeunique=makeunique,
indicator=source, validate=validate,
left_rename=first(renamecols), right_rename=last(renamecols),
matchmissing=matchmissing)
end
"""
outerjoin(df1, df2; on, makeunique=false, source=nothing, validate=(false, false),
renamecols=(identity => identity), matchmissing=:error)
outerjoin(df1, df2, dfs...; on, makeunique = false,
validate = (false, false), matchmissing=:error)
Perform an outer join of two or more data frame objects and return a `DataFrame`
containing the result. An outer join includes rows with keys that appear in any
of the passed data frames.
The order of rows in the result is undefined and may change in the future releases.
In the returned data frame the type of the columns on which the data frames are
joined is determined by the element type of these columns both `df1` and `df2`.
This behavior may change in future releases.
# Arguments
- `df1`, `df2`, `dfs...` : the `AbstractDataFrames` to be joined
# Keyword Arguments
- `on` : A column name to join `df1` and `df2` on. If the columns on which
`df1` and `df2` will be joined have different names, then a `left=>right`
pair can be passed. It is also allowed to perform a join on multiple columns,
in which case a vector of column names or column name pairs can be passed
(mixing names and pairs is allowed). If more than two data frames are joined
then only a column name or a vector of column names are allowed.
`on` is a required argument.
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found in columns not joined on;
if `true`, duplicate names will be suffixed with `_i`
(`i` starting at 1 for the first duplicate).
- `source` : Default: `nothing`. If a `Symbol` or string, adds indicator
column with the given name for whether a row appeared in only `df1` (`"left_only"`),
only `df2` (`"right_only"`) or in both (`"both"`). If the name is already in use,
the column name will be modified if `makeunique=true`.
This argument is only supported when joining exactly two data frames.
- `validate` : whether to check that columns passed as the `on` argument
define unique keys in each input data frame (according to `isequal`).
Can be a tuple or a pair, with the first element indicating whether to
run check for `df1` and the second element for `df2`.
By default no check is performed.
- `renamecols` : a `Pair` specifying how columns of left and right data frames should
be renamed in the resulting data frame. Each element of the pair can be a
string or a `Symbol` can be passed in which case it is appended to the original
column name; alternatively a function can be passed in which case it is applied
to each column name, which is passed to it as a `String`. Note that `renamecols`
does not affect `on` columns, whose names are always taken from the left
data frame and left unchanged.
- `matchmissing` : if equal to `:error` throw an error if `missing` is present
in `on` columns; if equal to `:equal` then `missing` is allowed and missings are
matched; `isequal` is used for comparisons of rows for equality
All columns of the returned data table will support missing values.
It is not allowed to join on columns that contain `NaN` or `-0.0` in real or
imaginary part of the number. If you need to perform a join on such values use
CategoricalArrays.jl and transform a column containing such values into a
`CategoricalVector`.
When merging `on` categorical columns that differ in the ordering of their
levels, the ordering of the left data frame takes precedence over the ordering
of the right data frame.
If more than two data frames are passed, the join is performed
recursively with left associativity.
In this case the `indicator` keyword argument is not supported
and `validate` keyword argument is applied recursively with left associativity.
See also: [`innerjoin`](@ref), [`leftjoin`](@ref), [`rightjoin`](@ref),
[`semijoin`](@ref), [`antijoin`](@ref), [`crossjoin`](@ref).
# Examples
```jldoctest
julia> name = DataFrame(ID = [1, 2, 3], Name = ["John Doe", "Jane Doe", "Joe Blogs"])
3×2 DataFrame
Row │ ID Name
│ Int64 String
─────┼──────────────────
1 │ 1 John Doe
2 │ 2 Jane Doe
3 │ 3 Joe Blogs
julia> job = DataFrame(ID = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ ID Job
│ Int64 String
─────┼───────────────
1 │ 1 Lawyer
2 │ 2 Doctor
3 │ 4 Farmer
julia> outerjoin(name, job, on = :ID)
4×3 DataFrame
Row │ ID Name Job
│ Int64 String? String?
─────┼───────────────────────────
1 │ 1 John Doe Lawyer
2 │ 2 Jane Doe Doctor
3 │ 3 Joe Blogs missing
4 │ 4 missing Farmer
julia> job2 = DataFrame(identifier = [1, 2, 4], Job = ["Lawyer", "Doctor", "Farmer"])
3×2 DataFrame
Row │ identifier Job
│ Int64 String