/
dataframe.jl
1606 lines (1424 loc) · 60.7 KB
/
dataframe.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
"""
DataFrame <: AbstractDataFrame
An AbstractDataFrame that stores a set of named columns
The columns are normally AbstractVectors stored in memory,
particularly a Vector or CategoricalVector.
# Constructors
```julia
DataFrame(pairs::Pair...; makeunique::Bool=false, copycols::Bool=true)
DataFrame(pairs::AbstractVector{<:Pair}; makeunique::Bool=false, copycols::Bool=true)
DataFrame(ds::AbstractDict; copycols::Bool=true)
DataFrame(kwargs..., copycols::Bool=true)
DataFrame(columns::AbstractVecOrMat, names::Union{AbstractVector, Symbol};
makeunique::Bool=false, copycols::Bool=true)
DataFrame(table; copycols::Bool=true)
DataFrame(::DataFrameRow)
DataFrame(::GroupedDataFrame; keepkeys::Bool=true)
```
# Keyword arguments
- `copycols` : whether vectors passed as columns should be copied; by default set
to `true` and the vectors are copied; if set to `false` then the constructor
will still copy the passed columns if it is not possible to construct a
`DataFrame` without materializing new columns.
- `makeunique` : if `false` (the default), an error will be raised
(note that not all constructors support these keyword arguments)
# Details on behavior of different constructors
It is allowed to pass a vector of `Pair`s, a list of `Pair`s as positional
arguments, or a list of keyword arguments. In this case each pair is considered
to represent a column name to column value mapping and column name must be a
`Symbol` or string. Alternatively a dictionary can be passed to the constructor
in which case its entries are considered to define the column name and column
value pairs. If the dictionary is a `Dict` then column names will be sorted in
the returned `DataFrame`.
In all the constructors described above column value can be a vector which is
consumed as is or an object of any other type (except `AbstractArray`). In the
latter case the passed value is automatically repeated to fill a new vector of
the appropriate length. As a particular rule values stored in a `Ref` or a
`0`-dimensional `AbstractArray` are unwrapped and treated in the same way.
It is also allowed to pass a vector of vectors or a matrix as as the first
argument. In this case the second argument must be
a vector of `Symbol`s or strings specifying column names, or the symbol `:auto`
to generate column names `x1`, `x2`, ... automatically.
If a single positional argument is passed to a `DataFrame` constructor then it
is assumed to be of type that implements the
[Tables.jl](https://github.com/JuliaData/Tables.jl) interface using which the
returned `DataFrame` is materialized.
Finally it is allowed to construct a `DataFrame` from a `DataFrameRow` or a
`GroupedDataFrame`. In the latter case the `keepkeys` keyword argument specifies
whether the resulting `DataFrame` should contain the grouping columns of the
passed `GroupedDataFrame` and the order of rows in the result follows the order
of groups in the `GroupedDataFrame` passed.
# Notes
The `DataFrame` constructor by default copies all columns vectors passed to it.
Pass the `copycols=false` keyword argument (where supported) to reuse vectors without
copying them.
By default an error will be raised if duplicates in column names are found. Pass
`makeunique=true` keyword argument (where supported) to accept duplicate names,
in which case they will be suffixed with `_i` (`i` starting at 1 for the first
duplicate).
If an `AbstractRange` is passed to a `DataFrame` constructor as a column it is
always collected to a `Vector` (even if `copycols=false`). As a general rule
`AbstractRange` values are always materialized to a `Vector` by all functions in
DataFrames.jl before being stored in a `DataFrame`.
The `DataFrame` type is designed to allow column types to vary and to be
dynamically changed also after it is constructed. Therefore `DataFrame`s are not
type stable. For performance-critical code that requires type-stability either
use the functionality provided by `select`/`transform`/`combine` functions, use
`Tables.columntable` and `Tables.namedtupleiterator` functions, use barrier
functions, or provide type assertions to the variables that hold columns
extracted from a `DataFrame`.
# Examples
```julia
julia> DataFrame((a=[1,2], b=[3,4])) # Tables.jl table constructor
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 3 │
│ 2 │ 2 │ 4 │
julia> DataFrame([(a=1, b=0), (a=2, b=0)]) # Tables.jl table constructor
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 0 │
│ 2 │ 2 │ 0 │
julia> DataFrame("a" => 1:2, "b" => 0) # Pair constructor
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 0 │
│ 2 │ 2 │ 0 │
julia> DataFrame([:a => 1:2, :b => 0]) # vector of Pairs constructor
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 0 │
│ 2 │ 2 │ 0 │
julia> DataFrame(Dict(:a => 1:2, :b => 0)) # dictionary constructor
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 0 │
│ 2 │ 2 │ 0 │
julia> DataFrame(a=1:2, b=0) # keyword argument constructor
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 0 │
│ 2 │ 2 │ 0 │
julia> DataFrame([[1, 2], [0, 0]], [:a, :b]) # vector of vectors constructor
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 0 │
│ 2 │ 2 │ 0 │
julia> DataFrame([1 0; 2 0], :auto) # matrix constructor
2×2 DataFrame
│ Row │ x1 │ x2 │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 0 │
│ 2 │ 2 │ 0 │
```
"""
struct DataFrame <: AbstractDataFrame
columns::Vector{AbstractVector}
colindex::Index
# the inner constructor should not be used directly
function DataFrame(columns::Union{Vector{Any}, Vector{AbstractVector}},
colindex::Index; copycols::Bool=true)
if length(columns) == length(colindex) == 0
return new(AbstractVector[], Index())
elseif length(columns) != length(colindex)
throw(DimensionMismatch("Number of columns ($(length(columns))) and number of" *
" column names ($(length(colindex))) are not equal"))
end
len = -1
firstvec = -1
for (i, col) in enumerate(columns)
if col isa AbstractVector
if len == -1
len = length(col)
firstvec = i
elseif len != length(col)
n1 = _names(colindex)[firstvec]
n2 = _names(colindex)[i]
throw(DimensionMismatch("column :$n1 has length $len and column " *
":$n2 has length $(length(col))"))
end
end
end
len == -1 && (len = 1) # we got no vectors so make one row of scalars
# we write into columns as we know that it is guaranteed
# that it was freshly allocated in the outer constructor
for (i, col) in enumerate(columns)
# check for vectors first as they are most common
if col isa AbstractRange
columns[i] = collect(col)
elseif col isa AbstractVector
columns[i] = copycols ? copy(col) : col
elseif col isa Union{AbstractArray{<:Any, 0}, Ref}
x = col[]
columns[i] = fill!(Tables.allocatecolumn(typeof(x), len), x)
else
if col isa AbstractArray
throw(ArgumentError("adding AbstractArray other than AbstractVector" *
" as a column of a data frame is not allowed"))
end
columns[i] = fill!(Tables.allocatecolumn(typeof(col), len), col)
end
end
new(convert(Vector{AbstractVector}, columns), colindex)
end
end
DataFrame(df::DataFrame; copycols::Bool=true) = copy(df, copycols=copycols)
function DataFrame(pairs::Pair{Symbol,<:Any}...; makeunique::Bool=false,
copycols::Bool=true)::DataFrame
colnames = [Symbol(k) for (k,v) in pairs]
columns = Any[v for (k,v) in pairs]
return DataFrame(columns, Index(colnames, makeunique=makeunique),
copycols=copycols)
end
function DataFrame(pairs::Pair{<:AbstractString,<:Any}...; makeunique::Bool=false,
copycols::Bool=true)::DataFrame
colnames = [Symbol(k) for (k,v) in pairs]
columns = Any[v for (k,v) in pairs]
return DataFrame(columns, Index(colnames, makeunique=makeunique),
copycols=copycols)
end
# this is needed as a workaround for Tables.jl dispatch
function DataFrame(pairs::AbstractVector{<:Pair}; makeunique::Bool=false,
copycols::Bool=true)
if isempty(pairs)
return DataFrame()
else
if !(all(((k,v),) -> k isa Symbol, pairs) || all(((k,v),) -> k isa AbstractString, pairs))
throw(ArgumentError("All column names must be either Symbols or strings (mixing is not allowed)"))
end
colnames = [Symbol(k) for (k,v) in pairs]
columns = Any[v for (k,v) in pairs]
return DataFrame(columns, Index(colnames, makeunique=makeunique),
copycols=copycols)
end
end
function DataFrame(d::AbstractDict; copycols::Bool=true)
if all(k -> k isa Symbol, keys(d))
colnames = collect(Symbol, keys(d))
elseif all(k -> k isa AbstractString, keys(d))
colnames = [Symbol(k) for k in keys(d)]
else
throw(ArgumentError("All column names must be either Symbols or strings (mixing is not allowed)"))
end
colindex = Index(colnames)
columns = Any[v for v in values(d)]
df = DataFrame(columns, colindex, copycols=copycols)
d isa Dict && select!(df, sort!(propertynames(df)))
return df
end
function DataFrame(; kwargs...)
if isempty(kwargs)
DataFrame([], Index())
else
cnames = Symbol[]
columns = Any[]
copycols = true
for (kw, val) in kwargs
if kw === :copycols
if val isa Bool
copycols = val
else
throw(ArgumentError("the `copycols` keyword argument must be Boolean"))
end
elseif kw === :makeunique
throw(ArgumentError("the `makeunique` keyword argument is not allowed" *
" in DataFrame(; kwargs...) constructor"))
else
push!(cnames, kw)
push!(columns, val)
end
end
DataFrame(columns, Index(cnames), copycols=copycols)
end
end
function DataFrame(columns::AbstractVector, cnames::AbstractVector{Symbol};
makeunique::Bool=false, copycols::Bool=true)::DataFrame
if !(eltype(columns) <: AbstractVector) && !all(col -> isa(col, AbstractVector), columns)
throw(ArgumentError("columns argument must be a vector of AbstractVector objects"))
end
return DataFrame(collect(AbstractVector, columns),
Index(convert(Vector{Symbol}, cnames), makeunique=makeunique),
copycols=copycols)
end
DataFrame(columns::AbstractVector, cnames::AbstractVector{<:AbstractString};
makeunique::Bool=false, copycols::Bool=true) =
DataFrame(columns, Symbol.(cnames), makeunique=makeunique, copycols=copycols)
DataFrame(columns::AbstractVector{<:AbstractVector}, cnames::AbstractVector{Symbol};
makeunique::Bool=false, copycols::Bool=true)::DataFrame =
DataFrame(collect(AbstractVector, columns),
Index(convert(Vector{Symbol}, cnames), makeunique=makeunique),
copycols=copycols)
DataFrame(columns::AbstractVector{<:AbstractVector}, cnames::AbstractVector{<:AbstractString};
makeunique::Bool=false, copycols::Bool=true) =
DataFrame(columns, Symbol.(cnames); makeunique=makeunique, copycols=copycols)
function DataFrame(columns::AbstractVector, cnames::Symbol; copycols::Bool=true)
if cnames !== :auto
throw(ArgumentError("if the first positional argument to DataFrame " *
"constructor is a vector of vectors and the second " *
"positional argument is passed then the second " *
"argument must be a vector of column names or :auto"))
end
return DataFrame(columns, gennames(length(columns)), copycols=copycols)
end
DataFrame(columns::AbstractMatrix, cnames::AbstractVector{Symbol}; makeunique::Bool=false) =
DataFrame(AbstractVector[columns[:, i] for i in 1:size(columns, 2)], cnames,
makeunique=makeunique, copycols=false)
DataFrame(columns::AbstractMatrix, cnames::AbstractVector{<:AbstractString};
makeunique::Bool=false) =
DataFrame(columns, Symbol.(cnames); makeunique=makeunique)
function DataFrame(columns::AbstractMatrix, cnames::Symbol)
if cnames !== :auto
throw(ArgumentError("if the first positional argument to DataFrame " *
"constructor is a matrix and a second " *
"positional argument is passed then the second " *
"argument must be a vector of column names or :auto"))
end
return DataFrame(columns, gennames(size(columns, 2)), makeunique=false)
end
##############################################################################
##
## AbstractDataFrame interface
##
##############################################################################
index(df::DataFrame) = getfield(df, :colindex)
_columns(df::DataFrame) = getfield(df, :columns)
# note: these type assertions are required to pass tests
nrow(df::DataFrame) = ncol(df) > 0 ? length(_columns(df)[1])::Int : 0
ncol(df::DataFrame) = length(index(df))
##############################################################################
##
## DataFrame consistency check
##
##############################################################################
corrupt_msg(df::DataFrame, i::Integer) =
"Data frame is corrupt: length of column " *
":$(_names(df)[i]) ($(length(df[!, i]))) " *
"does not match length of column 1 ($(length(df[!, 1]))). " *
"The column vector has likely been resized unintentionally " *
"(either directly or because it is shared with another data frame)."
function _check_consistency(df::DataFrame)
cols, idx = _columns(df), index(df)
ncols = length(cols)
@assert length(idx.names) == length(idx.lookup) == ncols
ncols == 0 && return nothing
nrows = length(cols[1])
for i in 2:length(cols)
@assert length(cols[i]) == nrows corrupt_msg(df, i)
end
nothing
end
_check_consistency(df::AbstractDataFrame) = _check_consistency(parent(df))
##############################################################################
##
## getindex() definitions
##
##############################################################################
# df[SingleRowIndex, SingleColumnIndex] => Scalar
@inline function Base.getindex(df::DataFrame, row_ind::Integer,
col_ind::Union{Signed, Unsigned})
cols = _columns(df)
@boundscheck begin
if !checkindex(Bool, axes(cols, 1), col_ind)
throw(BoundsError(df, (row_ind, col_ind)))
end
if !checkindex(Bool, axes(df, 1), row_ind)
throw(BoundsError(df, (row_ind, col_ind)))
end
end
@inbounds cols[col_ind][row_ind]
end
@inline function Base.getindex(df::DataFrame, row_ind::Integer,
col_ind::SymbolOrString)
selected_column = index(df)[col_ind]
@boundscheck if !checkindex(Bool, axes(df, 1), row_ind)
throw(BoundsError(df, (row_ind, col_ind)))
end
@inbounds _columns(df)[selected_column][row_ind]
end
# df[MultiRowIndex, SingleColumnIndex] => AbstractVector, copy
@inline function Base.getindex(df::DataFrame, row_inds::AbstractVector, col_ind::ColumnIndex)
selected_column = index(df)[col_ind]
@boundscheck if !checkindex(Bool, axes(df, 1), row_inds)
throw(BoundsError(df, (row_inds, col_ind)))
end
@inbounds return _columns(df)[selected_column][row_inds]
end
@inline Base.getindex(df::DataFrame, row_inds::Not, col_ind::ColumnIndex) =
df[axes(df, 1)[row_inds], col_ind]
# df[:, SingleColumnIndex] => AbstractVector
function Base.getindex(df::DataFrame, row_inds::Colon, col_ind::ColumnIndex)
selected_column = index(df)[col_ind]
copy(_columns(df)[selected_column])
end
# df[!, SingleColumnIndex] => AbstractVector, the same vector
@inline function Base.getindex(df::DataFrame, ::typeof(!), col_ind::Union{Signed, Unsigned})
cols = _columns(df)
@boundscheck if !checkindex(Bool, axes(cols, 1), col_ind)
throw(BoundsError(df, (!, col_ind)))
end
@inbounds cols[col_ind]
end
function Base.getindex(df::DataFrame, ::typeof(!), col_ind::SymbolOrString)
selected_column = index(df)[col_ind]
return _columns(df)[selected_column]
end
# df[MultiRowIndex, MultiColumnIndex] => DataFrame
@inline function Base.getindex(df::DataFrame, row_inds::AbstractVector{T},
col_inds::MultiColumnIndex) where T
@boundscheck if !checkindex(Bool, axes(df, 1), row_inds)
throw(BoundsError(df, (row_inds, col_inds)))
end
selected_columns = index(df)[col_inds]
# Computing integer indices once for all columns is faster
selected_rows = T === Bool ? findall(row_inds) : row_inds
new_columns = AbstractVector[dv[selected_rows] for dv in _columns(df)[selected_columns]]
return DataFrame(new_columns, Index(_names(df)[selected_columns]), copycols=false)
end
@inline function Base.getindex(df::DataFrame, row_inds::AbstractVector{T}, ::Colon) where T
@boundscheck if !checkindex(Bool, axes(df, 1), row_inds)
throw(BoundsError(df, (row_inds, :)))
end
# Computing integer indices once for all columns is faster
selected_rows = T === Bool ? findall(row_inds) : row_inds
new_columns = AbstractVector[dv[selected_rows] for dv in _columns(df)]
return DataFrame(new_columns, copy(index(df)), copycols=false)
end
@inline Base.getindex(df::DataFrame, row_inds::Not,
col_inds::MultiColumnIndex) =
df[axes(df, 1)[row_inds], col_inds]
# df[:, MultiColumnIndex] => DataFrame
Base.getindex(df::DataFrame, row_ind::Colon,
col_inds::MultiColumnIndex) =
select(df, col_inds, copycols=true)
# df[!, MultiColumnIndex] => DataFrame
Base.getindex(df::DataFrame, row_ind::typeof(!),
col_inds::MultiColumnIndex) =
select(df, col_inds, copycols=false)
##############################################################################
##
## setindex!()
##
##############################################################################
function nextcolname(df::DataFrame)
col = Symbol(string("x", ncol(df) + 1))
hasproperty(df, col) || return col
i = 1
while true
col = Symbol(string("x", ncol(df) + 1, "_", i))
hasproperty(df, col) || return col
i += 1
end
end
# Will automatically add a new column if needed
function insert_single_column!(df::DataFrame, v::AbstractVector, col_ind::ColumnIndex)
if ncol(df) != 0 && nrow(df) != length(v)
throw(ArgumentError("New columns must have the same length as old columns"))
end
dv = isa(v, AbstractRange) ? collect(v) : v
if haskey(index(df), col_ind)
j = index(df)[col_ind]
_columns(df)[j] = dv
else
if col_ind isa SymbolOrString
push!(index(df), Symbol(col_ind))
push!(_columns(df), dv)
else
throw(ArgumentError("Cannot assign to non-existent column: $col_ind"))
end
end
return dv
end
function insert_single_entry!(df::DataFrame, v::Any, row_ind::Integer, col_ind::ColumnIndex)
if haskey(index(df), col_ind)
_columns(df)[index(df)[col_ind]][row_ind] = v
return v
else
throw(ArgumentError("Cannot assign to non-existent column: $col_ind"))
end
end
function insert_multiple_entries!(df::DataFrame,
v::Any,
row_inds::AbstractVector,
col_ind::ColumnIndex)
if haskey(index(df), col_ind)
_columns(df)[index(df)[col_ind]][row_inds] .= v
return v
else
throw(ArgumentError("Cannot assign to non-existent column: $col_ind"))
end
end
# df[!, SingleColumnIndex] = AbstractVector
function Base.setindex!(df::DataFrame, v::AbstractVector, ::typeof(!), col_ind::ColumnIndex)
insert_single_column!(df, v, col_ind)
return df
end
# df.col = AbstractVector
# separate methods are needed due to dispatch ambiguity
Base.setproperty!(df::DataFrame, col_ind::Symbol, v::AbstractVector) =
(df[!, col_ind] = v)
Base.setproperty!(df::DataFrame, col_ind::AbstractString, v::AbstractVector) =
(df[!, col_ind] = v)
Base.setproperty!(::DataFrame, col_ind::Symbol, v::Any) =
throw(ArgumentError("It is only allowed to pass a vector as a column of a DataFrame." *
"Instead use `df[!, col_ind] .= v` if you want to use broadcasting."))
Base.setproperty!(::DataFrame, col_ind::AbstractString, v::Any) =
throw(ArgumentError("It is only allowed to pass a vector as a column of a DataFrame." *
"Instead use `df[!, col_ind] .= v` if you want to use broadcasting."))
# df[SingleRowIndex, SingleColumnIndex] = Single Item
function Base.setindex!(df::DataFrame, v::Any, row_ind::Integer, col_ind::ColumnIndex)
insert_single_entry!(df, v, row_ind, col_ind)
return df
end
# df[SingleRowIndex, MultiColumnIndex] = value
# the method for value of type DataFrameRow, AbstractDict and NamedTuple
# is defined in dataframerow.jl
for T in MULTICOLUMNINDEX_TUPLE
@eval function Base.setindex!(df::DataFrame,
v::Union{Tuple, AbstractArray},
row_ind::Integer,
col_inds::$T)
idxs = index(df)[col_inds]
if length(v) != length(idxs)
throw(DimensionMismatch("$(length(idxs)) columns were selected but the assigned" *
" collection contains $(length(v)) elements"))
end
for (i, x) in zip(idxs, v)
df[row_ind, i] = x
end
return df
end
end
# df[MultiRowIndex, SingleColumnIndex] = AbstractVector
for T in (:AbstractVector, :Not, :Colon)
@eval function Base.setindex!(df::DataFrame,
v::AbstractVector,
row_inds::$T,
col_ind::ColumnIndex)
if row_inds isa Colon && !haskey(index(df), col_ind)
df[!, col_ind] = copy(v)
return df
end
x = df[!, col_ind]
x[row_inds] = v
return df
end
end
# df[MultiRowIndex, MultiColumnIndex] = AbstractDataFrame
for T1 in (:AbstractVector, :Not, :Colon),
T2 in MULTICOLUMNINDEX_TUPLE
@eval function Base.setindex!(df::DataFrame,
new_df::AbstractDataFrame,
row_inds::$T1,
col_inds::$T2)
idxs = index(df)[col_inds]
if view(_names(df), idxs) != _names(new_df)
throw(ArgumentError("column names in source and target do not match"))
end
for (j, col) in enumerate(idxs)
df[row_inds, col] = new_df[!, j]
end
return df
end
end
for T in MULTICOLUMNINDEX_TUPLE
@eval function Base.setindex!(df::DataFrame,
new_df::AbstractDataFrame,
row_inds::typeof(!),
col_inds::$T)
idxs = index(df)[col_inds]
if view(_names(df), idxs) != _names(new_df)
throw(ArgumentError("Column names in source and target data frames do not match"))
end
for (j, col) in enumerate(idxs)
# make sure we make a copy on assignment
df[!, col] = new_df[:, j]
end
return df
end
end
# df[MultiRowIndex, MultiColumnIndex] = AbstractMatrix
for T1 in (:AbstractVector, :Not, :Colon, :(typeof(!))),
T2 in MULTICOLUMNINDEX_TUPLE
@eval function Base.setindex!(df::DataFrame,
mx::AbstractMatrix,
row_inds::$T1,
col_inds::$T2)
idxs = index(df)[col_inds]
if size(mx, 2) != length(idxs)
throw(DimensionMismatch("number of selected columns ($(length(idxs)))" *
" and number of columns in" *
" matrix ($(size(mx, 2))) do not match"))
end
for (j, col) in enumerate(idxs)
df[row_inds, col] = (row_inds === !) ? mx[:, j] : view(mx, :, j)
end
return df
end
end
##############################################################################
##
## Mutating methods
##
##############################################################################
"""
insertcols!(df::DataFrame, [col], (name=>val)::Pair...;
makeunique::Bool=false, copycols::Bool=true)
Insert a column into a data frame in place. Return the updated `DataFrame`.
If `col` is omitted it is set to `ncol(df)+1`
(the column is inserted as the last column).
# Arguments
- `df` : the DataFrame to which we want to add columns
- `col` : a position at which we want to insert a column, passed as an integer
or a column name (a string or a `Symbol`); the column selected with `col`
and columns following it are shifted to the right in `df` after the operation
- `name` : the name of the new column
- `val` : an `AbstractVector` giving the contents of the new column or a value of any
type other than `AbstractArray` which will be repeated to fill a new vector;
As a particular rule a values stored in a `Ref` or a `0`-dimensional `AbstractArray`
are unwrapped and treated in the same way.
- `makeunique` : Defines what to do if `name` already exists in `df`;
if it is `false` an error will be thrown; if it is `true` a new unique name will
be generated by adding a suffix
- `copycols` : whether vectors passed as columns should be copied
If `val` is an `AbstractRange` then the result of `collect(val)` is inserted.
# Examples
```jldoctest
julia> d = DataFrame(a=1:3)
3×1 DataFrame
│ Row │ a │
│ │ Int64 │
├─────┼───────┤
│ 1 │ 1 │
│ 2 │ 2 │
│ 3 │ 3 │
julia> insertcols!(d, 1, :b => 'a':'c')
3×2 DataFrame
│ Row │ b │ a │
│ │ Char │ Int64 │
├─────┼──────┼───────┤
│ 1 │ 'a' │ 1 │
│ 2 │ 'b' │ 2 │
│ 3 │ 'c' │ 3 │
julia> insertcols!(d, 2, :c => 2:4, :c => 3:5, makeunique=true)
3×4 DataFrame
│ Row │ b │ c │ c_1 │ a │
│ │ Char │ Int64 │ Int64 │ Int64 │
├─────┼──────┼───────┼───────┼───────┤
│ 1 │ 'a' │ 2 │ 3 │ 1 │
│ 2 │ 'b' │ 3 │ 4 │ 2 │
│ 3 │ 'c' │ 4 │ 5 │ 3 │
```
"""
function insertcols!(df::DataFrame, col::ColumnIndex, name_cols::Pair{Symbol,<:Any}...;
makeunique::Bool=false, copycols::Bool=true)
col_ind = Int(col isa SymbolOrString ? columnindex(df, col) : col)
if !(0 < col_ind <= ncol(df) + 1)
throw(ArgumentError("attempt to insert a column to a data frame with " *
"$(ncol(df)) columns at index $col_ind"))
end
if !makeunique
if !allunique(first.(name_cols))
throw(ArgumentError("Names of columns to be inserted into a data frame " *
"must be unique when `makeunique=true`"))
end
for (n, _) in name_cols
if hasproperty(df, n)
throw(ArgumentError("Column $n is already present in the data frame " *
"which is not allowed when `makeunique=true`"))
end
end
end
if ncol(df) == 0
target_row_count = -1
else
target_row_count = nrow(df)
end
for (n, v) in name_cols
if v isa AbstractVector
if target_row_count == -1
target_row_count = length(v)
elseif length(v) != target_row_count
if target_row_count == nrow(df)
throw(DimensionMismatch("length of new column $n which is " *
"$(length(v)) must match the number " *
"of rows in data frame ($(nrow(df)))"))
else
throw(DimensionMismatch("all vectors passed to be inserted into " *
"a data frame must have the same length"))
end
end
elseif v isa AbstractArray && ndims(v) > 1
throw(ArgumentError("adding AbstractArray other than AbstractVector as " *
"a column of a data frame is not allowed"))
end
end
if target_row_count == -1
target_row_count = 1
end
for (name, item) in name_cols
if !(item isa AbstractVector)
if item isa Union{AbstractArray{<:Any, 0}, Ref}
x = item[]
item_new = fill!(Tables.allocatecolumn(typeof(x), target_row_count), x)
else
@assert !(item isa AbstractArray)
item_new = fill!(Tables.allocatecolumn(typeof(item), target_row_count), item)
end
elseif item isa AbstractRange
item_new = collect(item)
elseif copycols
item_new = copy(item)
else
item_new = item
end
if ncol(df) == 0
df[!, name] = item_new
else
if hasproperty(df, name)
@assert makeunique
k = 1
while true
nn = Symbol("$(name)_$k")
if !hasproperty(df, nn)
name = nn
break
end
k += 1
end
end
insert!(index(df), col_ind, name)
insert!(_columns(df), col_ind, item_new)
end
col_ind += 1
end
return df
end
insertcols!(df::DataFrame, col::ColumnIndex, name_cols::Pair{<:AbstractString,<:Any}...;
makeunique::Bool=false, copycols::Bool=true) =
insertcols!(df, col, (Symbol(n) => v for (n,v) in name_cols)...,
makeunique=makeunique, copycols=copycols)
insertcols!(df::DataFrame, name_cols::Pair{Symbol,<:Any}...;
makeunique::Bool=false, copycols::Bool=true) =
insertcols!(df, ncol(df)+1, name_cols..., makeunique=makeunique, copycols=copycols)
insertcols!(df::DataFrame, name_cols::Pair{<:AbstractString,<:Any}...;
makeunique::Bool=false, copycols::Bool=true) =
insertcols!(df, (Symbol(n) => v for (n,v) in name_cols)...,
makeunique=makeunique, copycols=copycols)
function insertcols!(df::DataFrame, col::Int=ncol(df)+1; makeunique::Bool=false, name_cols...)
if !(0 < col <= ncol(df) + 1)
throw(ArgumentError("attempt to insert a column to a data frame with " *
"$(ncol(df)) columns at index $col"))
end
if !isempty(name_cols)
# an explicit error is thrown as keyword argument was supported in the past
throw(ArgumentError("inserting colums using a keyword argument is not supported," *
" pass a Pair as a positional argument instead"))
end
return df
end
"""
copy(df::DataFrame; copycols::Bool=true)
Copy data frame `df`.
If `copycols=true` (the default), return a new `DataFrame` holding
copies of column vectors in `df`.
If `copycols=false`, return a new `DataFrame` sharing column vectors with `df`.
"""
function Base.copy(df::DataFrame; copycols::Bool=true)
if copycols
df[:, :]
else
DataFrame(_columns(df), _names(df), copycols=false)
end
end
"""
delete!(df::DataFrame, inds)
Delete rows specified by `inds` from a `DataFrame` `df` in place and return it.
Internally `deleteat!` is called for all columns so `inds` must be:
a vector of sorted and unique integers, a boolean vector, an integer, or `Not`.
# Examples
```jldoctest
julia> d = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │
julia> delete!(d, 2)
2×2 DataFrame
│ Row │ a │ b │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 3 │ 6 │
```
"""
function Base.delete!(df::DataFrame, inds)
if !isempty(inds) && size(df, 2) == 0
throw(BoundsError(df, (inds, :)))
end
# we require ind to be stored and unique like in Base
# otherwise an error will be thrown and the data frame will get corrupted
foreach(col -> deleteat!(col, inds), _columns(df))
return df
end
function Base.delete!(df::DataFrame, inds::AbstractVector{Bool})
if length(inds) != size(df, 1)
throw(BoundsError(df, (inds, :)))
end
drop = findall(inds)
foreach(col -> deleteat!(col, drop), _columns(df))
return df
end
Base.delete!(df::DataFrame, inds::Not) = delete!(df, axes(df, 1)[inds])
"""
empty!(df::DataFrame)
Remove all rows from `df`, making each of its columns empty.
"""
function Base.empty!(df::DataFrame)
foreach(empty!, eachcol(df))
return df
end
##############################################################################
##
## Hcat specialization
##
##############################################################################
# hcat! for 2 arguments, only a vector or a data frame is allowed
function hcat!(df1::DataFrame, df2::AbstractDataFrame;
makeunique::Bool=false, copycols::Bool=true)
u = add_names(index(df1), index(df2), makeunique=makeunique)
for i in 1:length(u)
df1[!, u[i]] = copycols ? df2[:, i] : df2[!, i]
end
return df1
end
# definition required to avoid hcat! ambiguity
hcat!(df1::DataFrame, df2::DataFrame;
makeunique::Bool=false, copycols::Bool=true) =
invoke(hcat!, Tuple{DataFrame, AbstractDataFrame}, df1, df2,
makeunique=makeunique, copycols=copycols)::DataFrame
hcat!(df::DataFrame, x::AbstractVector; makeunique::Bool=false, copycols::Bool=true) =
hcat!(df, DataFrame(AbstractVector[x], [:x1], copycols=copycols),
makeunique=makeunique, copycols=copycols)
hcat!(x::AbstractVector, df::DataFrame; makeunique::Bool=false, copycols::Bool=true) =
hcat!(DataFrame(AbstractVector[x], [:x1], copycols=copycols), df,
makeunique=makeunique, copycols=copycols)
hcat!(x, df::DataFrame; makeunique::Bool=false, copycols::Bool=true) =
throw(ArgumentError("x must be AbstractVector or AbstractDataFrame"))
hcat!(df::DataFrame, x; makeunique::Bool=false, copycols::Bool=true) =
throw(ArgumentError("x must be AbstractVector or AbstractDataFrame"))
# hcat! for 1-n arguments
hcat!(df::DataFrame; makeunique::Bool=false, copycols::Bool=true) = df
hcat!(a::DataFrame, b, c...; makeunique::Bool=false, copycols::Bool=true) =
hcat!(hcat!(a, b, makeunique=makeunique, copycols=copycols),
c..., makeunique=makeunique, copycols=copycols)
# hcat
Base.hcat(df::DataFrame, x; makeunique::Bool=false, copycols::Bool=true) =
hcat!(copy(df, copycols=copycols), x,
makeunique=makeunique, copycols=copycols)
Base.hcat(df1::DataFrame, df2::AbstractDataFrame;
makeunique::Bool=false, copycols::Bool=true) =
hcat!(copy(df1, copycols=copycols), df2,
makeunique=makeunique, copycols=copycols)
Base.hcat(df1::DataFrame, df2::AbstractDataFrame, dfn::AbstractDataFrame...;
makeunique::Bool=false, copycols::Bool=true) =
hcat!(hcat(df1, df2, makeunique=makeunique, copycols=copycols), dfn...,
makeunique=makeunique, copycols=copycols)
##############################################################################
##
## Missing values support
##
##############################################################################
"""
allowmissing!(df::DataFrame, cols=:)
Convert columns `cols` of data frame `df` from element type `T` to
`Union{T, Missing}` to support missing values.
`cols` can be any column selector ($COLUMNINDEX_STR; $MULTICOLUMNINDEX_STR).
If `cols` is omitted all columns in the data frame are converted.
"""
function allowmissing! end
function allowmissing!(df::DataFrame, col::ColumnIndex)
df[!, col] = allowmissing(df[!, col])
return df
end
function allowmissing!(df::DataFrame, cols::AbstractVector{<:ColumnIndex})
for col in cols
allowmissing!(df, col)
end
return df
end
function allowmissing!(df::DataFrame, cols::AbstractVector{Bool})
length(cols) == size(df, 2) || throw(BoundsError(df, (!, cols)))
for (col, cond) in enumerate(cols)
cond && allowmissing!(df, col)
end
return df
end
allowmissing!(df::DataFrame, cols::MultiColumnIndex) =
allowmissing!(df, index(df)[cols])