forked from JuliaData/DataFrames.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataframe.jl
More file actions
executable file
·1559 lines (1321 loc) · 52.5 KB
/
dataframe.jl
File metadata and controls
executable file
·1559 lines (1321 loc) · 52.5 KB
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 `AbstractVector`s stored in memory,
particularly a `Vector`, `PooledVector` 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(table; copycols::Union{Bool, Nothing}=nothing)
DataFrame(table, names::AbstractVector;
makeunique::Bool=false, copycols::Union{Bool, Nothing}=nothing)
DataFrame(columns::AbstractVecOrMat, names::AbstractVector;
makeunique::Bool=false, copycols::Bool=true)
DataFrame(::DataFrameRow; copycols::Bool=true)
DataFrame(::GroupedDataFrame; copycols::Bool=true, 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. Note the `copycols=nothing`
default in the Tables.jl compatible constructor; it is provided as certain
input table types may have already made a copy of columns or the columns may
otherwise be immutable, in which case columns are not copied by default.
To force a copy in such cases, or to get mutable columns from an immutable
input table (like `Arrow.Table`), pass `copycols=true` explicitly.
- `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. Note that in this case
if the first argument is a matrix and `copycols=false` the columns of the created
`DataFrame` will be views of columns the source matrix.
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.
If two positional arguments are passed, where the second argument is an
`AbstractVector`, then the first argument is taken to be a table as described in
the previous paragraph, and columns names of the resulting data frame
are taken from the vector passed as the second positional argument.
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`.
`DataFrame` can store only columns that use 1-based indexing. Attempting
to store a vector using non-standard indexing raises an error.
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`.
Metadata: this function preserves all table and column-level metadata.
As a special case if a `GroupedDataFrame` is passed then
only `:note`-style metadata from parent of the `GroupedDataFrame` is preserved.
# Examples
```jldoctest
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
```
"""
mutable struct DataFrame <: AbstractDataFrame
columns::Vector{AbstractVector}
colindex::Index
metadata::Union{Nothing, Dict{String, Tuple{Any, Any}}}
colmetadata::Union{Nothing, Dict{Int, Dict{String, Tuple{Any, Any}}}}
# This is a helper field for optimizing performance of
# _drop_all_nonnote_metadata! and _drop_table_nonnote_metadata!
# so that if we only have :note-style metadata these functions are no-op.
# The contract is that if allnotemetadata=true then it is guaranteed that
# there are only :note-style metadata entries in the data frame.
# metadata! and colmetadata! functions appropriately set this field if a
# non-:note-style metadata is added.
allnotemetadata::Bool
# 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(), nothing, nothing, true)
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
len_val = len
# we write into columns as we know that it is guaranteed
# that it was freshly allocated in the outer constructor
if copycols && len_val >= 100_000 && length(columns) > 1 && Threads.nthreads() > 1
@sync for i in eachindex(columns)
@spawn columns[i] = _preprocess_column(columns[i], len_val, copycols)
end
else
for i in eachindex(columns)
columns[i] = _preprocess_column(columns[i], len_val, copycols)
end
end
for (i, col) in enumerate(columns)
firstindex(col) != 1 && _onebased_check_error(i, col)
end
return new(convert(Vector{AbstractVector}, columns), colindex, nothing, nothing, true)
end
end
function _preprocess_column(col::Any, len::Integer, copycols::Bool)
if col isa AbstractRange
return collect(col)
elseif col isa AbstractVector
return copycols ? copy(col) : col
elseif col isa Union{AbstractArray{<:Any, 0}, Ref}
x = col[]
return fill!(Tables.allocatecolumn(typeof(x), len), x)
elseif col isa AbstractArray
throw(ArgumentError("adding AbstractArray other than AbstractVector " *
"as a column of a data frame is not allowed"))
else
return fill!(Tables.allocatecolumn(typeof(col), len), col)
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)
if d isa Dict
select!(df, sort!(propertynames(df)))
else
# AbstractDict can potentially implement Tables.jl table interface
_copy_all_all_metadata!(df, d)
end
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)
return rename!(DataFrame(columns, copycols=copycols), cnames, makeunique=makeunique)
end
return DataFrame(collect(AbstractVector, columns),
Index(convert(Vector{Symbol}, cnames), makeunique=makeunique),
copycols=copycols)
end
function _name2symbol(str::AbstractVector)
if !(all(x -> x isa AbstractString, str) || all(x -> x isa Symbol, str))
throw(ArgumentError("All passed column names must be strings or Symbols"))
end
return Symbol[Symbol(s) for s in str]
end
DataFrame(columns::AbstractVector, cnames::AbstractVector;
makeunique::Bool=false, copycols::Bool=true) =
DataFrame(columns, _name2symbol(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;
makeunique::Bool=false, copycols::Bool=true) =
DataFrame(columns, _name2symbol(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
function DataFrame(columns::AbstractMatrix, cnames::AbstractVector{Symbol};
makeunique::Bool=false, copycols::Bool=true)
getter = copycols ? getindex : view
return DataFrame(AbstractVector[getter(columns, :, i) for i in 1:size(columns, 2)],
cnames, makeunique=makeunique, copycols=false)
end
DataFrame(columns::AbstractMatrix, cnames::AbstractVector;
makeunique::Bool=false, copycols::Bool=true) =
DataFrame(columns, _name2symbol(cnames); makeunique=makeunique, copycols=copycols)
function DataFrame(columns::AbstractMatrix, cnames::Symbol; copycols::Bool=true)
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, copycols=copycols)
end
# Discontinued constructors
DataFrame(matrix::Matrix) =
throw(ArgumentError("`DataFrame` constructor from a `Matrix` requires " *
"passing :auto as a second argument to automatically " *
"generate column names: `DataFrame(matrix, :auto)`"))
DataFrame(vecs::Vector{<:AbstractVector}) =
throw(ArgumentError("`DataFrame` constructor from a `Vector` of vectors requires " *
"passing :auto as a second argument to automatically " *
"generate column names: `DataFrame(vecs, :auto)`"))
DataFrame(column_eltypes::AbstractVector{<:Type}, cnames::AbstractVector{Symbol},
nrows::Integer=0; makeunique::Bool=false) =
throw(ArgumentError("`DataFrame` constructor with passed eltypes is " *
"not supported. Pass explicitly created columns to a " *
"`DataFrame` constructor instead."))
DataFrame(column_eltypes::AbstractVector{<:Type}, cnames::AbstractVector{<:AbstractString},
nrows::Integer=0; makeunique::Bool=false) =
throw(ArgumentError("`DataFrame` constructor with passed eltypes is " *
"not supported. Pass explicitly created columns to a " *
"`DataFrame` constructor instead."))
##############################################################################
##
## AbstractDataFrame interface
##
##############################################################################
index(df::DataFrame) = getfield(df, :colindex)
# this function grants the access to the internal storage of columns of the
# `DataFrame` and its use is unsafe. If the returned vector is mutated then
# make sure that:
# 1. `AbstractRange` columns are not added to a `DataFrame`
# 2. all inserted columns use 1-based indexing
# 3. after several mutating operations on the vector are performed
# each element (column) has the same length
# 4. if length of the vector is changed that the index of the `DataFrame`
# is adjusted appropriately
_columns(df::DataFrame) = getfield(df, :columns)
_onebased_check_error() =
throw(ArgumentError("Currently DataFrames.jl supports only columns " *
"that use 1-based indexing"))
_onebased_check_error(i, col) =
throw(ArgumentError("Currently DataFrames.jl supports only " *
"columns that use 1-based indexing, but " *
"column $i has starting index equal to $(firstindex(col))"))
"""
nrow(df::AbstractDataFrame)
Return the number of rows in an `AbstractDataFrame` `df`.
See also: [`ncol`](@ref), [`size`](@ref).
# Examples
```jldoctest
julia> df = DataFrame(i=1:10, x=rand(10), y=rand(["a", "b", "c"], 10));
julia> nrow(df)
10
```
""" # note: these type assertions are required to pass tests
nrow(df::DataFrame) = ncol(df) > 0 ? length(_columns(df)[1])::Int : 0
##############################################################################
##
## 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)
for (i, col) in enumerate(cols)
firstindex(col) != 1 && _onebased_check_error(i, col)
end
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
return @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
return @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
return @inbounds _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, ::Colon, col_ind::ColumnIndex)
selected_column = index(df)[col_ind]
return 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
return @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
function _threaded_getindex(selected_rows::AbstractVector,
selected_columns::AbstractVector,
df_columns::AbstractVector,
idx::AbstractIndex)
if length(selected_rows) >= 100_000 && Threads.nthreads() > 1
new_columns = Vector{AbstractVector}(undef, length(selected_columns))
@sync for i in eachindex(new_columns)
@spawn new_columns[i] = df_columns[selected_columns[i]][selected_rows]
end
return DataFrame(new_columns, idx, copycols=false)
else
return DataFrame(AbstractVector[df_columns[i][selected_rows] for i in selected_columns],
idx, copycols=false)
end
end
@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]
u = _names(df)[selected_columns]
lookup = Dict{Symbol, Int}(zip(u, 1:length(u)))
# use this constructor to avoid checking twice if column names are not
# duplicate as index(df)[col_inds] already checks this
idx = Index(lookup, u)
if length(selected_columns) == 1
new_df = DataFrame(AbstractVector[_columns(df)[selected_columns[1]][row_inds]],
idx, copycols=false)
else
# Computing integer indices once for all columns is faster
selected_rows = T === Bool ? _findall(row_inds) : row_inds
new_df = _threaded_getindex(selected_rows, selected_columns, _columns(df), idx)
end
_copy_all_note_metadata!(new_df, df)
return new_df
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
idx = copy(index(df))
if ncol(df) == 1
new_df = DataFrame(AbstractVector[_columns(df)[1][row_inds]], idx, copycols=false)
else
# Computing integer indices once for all columns is faster
selected_rows = T === Bool ? _findall(row_inds) : row_inds
new_df = _threaded_getindex(selected_rows, 1:ncol(df), _columns(df), idx)
end
_copy_all_note_metadata!(new_df, df)
return new_df
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, index(df)[col_inds], copycols=true)
# df[!, MultiColumnIndex] => DataFrame
Base.getindex(df::DataFrame, row_ind::typeof(!), col_inds::MultiColumnIndex) =
select(df, index(df)[col_inds], copycols=false)
##############################################################################
##
## setindex!()
##
##############################################################################
# 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
firstindex(dv) != 1 && _onebased_check_error()
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
_drop_all_nonnote_metadata!(df)
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
_drop_all_nonnote_metadata!(df)
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[!, i][row_ind] = x
end
_drop_all_nonnote_metadata!(df)
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
_drop_all_nonnote_metadata!(df)
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[!, col][row_inds] = new_df[!, j]
end
_drop_all_nonnote_metadata!(df)
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
# this will drop metadata appropriately
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)
# this will drop metadata appropriately
df[row_inds, col] = (row_inds === !) ? mx[:, j] : view(mx, :, j)
end
return df
end
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`.
Metadata: this function preserves all table-level and column-level metadata.
"""
function Base.copy(df::DataFrame; copycols::Bool=true)
cdf = DataFrame(copy(_columns(df)), copy(index(df)), copycols=copycols)
df_metadata = getfield(df, :metadata)
if !isnothing(df_metadata)
setfield!(cdf, :metadata, copy(df_metadata))
end
df_colmetadata = getfield(df, :colmetadata)
if !isnothing(df_colmetadata)
cdf_colmetadata = copy(df_colmetadata)
map!(copy, values(cdf_colmetadata))
setfield!(cdf, :colmetadata, cdf_colmetadata)
end
setfield!(cdf, :allnotemetadata, getfield(df, :allnotemetadata))
return cdf
end
"""
deleteat!(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` wrapping any valid selector.
$METADATA_FIXED
# Examples
```jldoctest
julia> df = 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> deleteat!(df, 2)
2×2 DataFrame
Row │ a b
│ Int64 Int64
─────┼──────────────
1 │ 1 4
2 │ 3 6
```
"""
Base.deleteat!(df::DataFrame, inds)
Base.deleteat!(df::DataFrame, ::Colon) = empty!(df)
function Base.deleteat!(df::DataFrame, inds::Integer)
inds isa Bool && throw(ArgumentError("Invalid index of type Bool"))
size(df, 2) == 0 && throw(BoundsError(df, (inds, :)))
return _deleteat!_helper(df, Int[inds])
end
function Base.deleteat!(df::DataFrame, inds::AbstractVector)
if isempty(inds)
_drop_all_nonnote_metadata!(df)
return df
elseif size(df, 2) == 0
throw(BoundsError(df, (inds, :)))
end
if Bool <: eltype(inds) && any(x -> x isa Bool, inds)
throw(ArgumentError("invalid index of type Bool"))
end
if !(eltype(inds) <: Integer || all(x -> x isa Integer, inds))
throw(ArgumentError("unsupported index $inds"))
end
if !issorted(inds, lt=<=)
throw(ArgumentError("Indices passed to deleteat! must be unique and sorted"))
end
return _deleteat!_helper(df, inds)
end
function Base.deleteat!(df::DataFrame, inds::AbstractVector{Bool})
if length(inds) != size(df, 1)
throw(BoundsError(df, (inds, :)))
end
return _deleteat!_helper(df, inds)
end
Base.deleteat!(df::DataFrame, inds::Not) =
_deleteat!_helper(df, axes(df, 1)[inds])
function _deleteat!_helper(df::DataFrame, drop)
cols = _columns(df)
if isempty(cols)
_drop_all_nonnote_metadata!(df)
return df
end
drop_local = drop
if any(c -> c === drop_local || Base.mightalias(c, drop_local), cols)
drop = copy(drop_local)
end
n = nrow(df)
col1 = cols[1]
deleteat!(col1, drop)
newn = length(col1)
@assert newn <= n
# the 0.06 threshold is heuristic; based on tests
# the assignment makes the code type-unstable but it is a small union
# so the overhead should be small
if drop isa AbstractVector{Bool} && newn < 0.06 * n
drop = findall(drop)
end
for i in 2:length(cols)
col = cols[i]
# this check is done to handle column aliases
if length(col) == n
deleteat!(col, drop)
end
end
for i in 1:length(cols)
# this should never happen, but we add it for safety
@assert length(cols[i]) == newn corrupt_msg(df, i)
end
_drop_all_nonnote_metadata!(df)
return df
end
"""
keepat!(df::DataFrame, inds)
Delete rows at all indices not 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` wrapping any valid selector.
$METADATA_FIXED
# Examples
```jldoctest
julia> df = 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> keepat!(df, [1, 3])
2×2 DataFrame
Row │ a b
│ Int64 Int64
─────┼──────────────
1 │ 1 4
2 │ 3 6
```
"""
keepat!(df::DataFrame, inds)
function keepat!(df::DataFrame, ::Colon)
_drop_all_nonnote_metadata!(df)
return df
end
function keepat!(df::DataFrame, inds::AbstractVector)
isempty(inds) && return empty!(df)
# this is required because of https://github.com/JuliaData/InvertedIndices.jl/issues/31
if !((eltype(inds) <: Integer) || all(x -> x isa Integer, inds))
throw(ArgumentError("unsupported index $inds"))
end
if Bool <: eltype(inds) && any(x -> x isa Bool, inds)
throw(ArgumentError("invalid index of type Bool"))
end
if !issorted(inds, lt=<=)
throw(ArgumentError("Indices passed to keepat! must be unique and sorted"))
end
return deleteat!(df, Not(inds))
end
function keepat!(df::DataFrame, inds::Integer)
inds isa Bool && throw(ArgumentError("Invalid index of type Bool"))
return deleteat!(df, Not(Int[inds]))
end