-
Notifications
You must be signed in to change notification settings - Fork 370
/
abstractdataframe.jl
2993 lines (2534 loc) · 97.9 KB
/
abstractdataframe.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
"""
AbstractDataFrame
An abstract type for which all concrete types expose an interface
for working with tabular data.
An `AbstractDataFrame` is a two-dimensional table with `Symbol`s or strings
for column names.
DataFrames.jl defines two types that are subtypes of `AbstractDataFrame`:
[`DataFrame`](@ref) and [`SubDataFrame`](@ref).
# Indexing and broadcasting
`AbstractDataFrame` can be indexed by passing two indices specifying
row and column selectors. The allowed indices are a superset of indices
that can be used for standard arrays. You can also access a single column
of an `AbstractDataFrame` using `getproperty` and `setproperty!` functions.
Columns can be selected using integers, `Symbol`s, or strings.
In broadcasting `AbstractDataFrame` behavior is similar to a `Matrix`.
A detailed description of `getindex`, `setindex!`, `getproperty`, `setproperty!`,
broadcasting and broadcasting assignment for data frames is given in the
["Indexing" section](https://juliadata.github.io/DataFrames.jl/stable/lib/indexing/)
of the manual.
"""
abstract type AbstractDataFrame end
"""
names(df::AbstractDataFrame, cols=:)
names(df::DataFrameRow, cols=:)
names(df::GroupedDataFrame, cols=:)
names(df::DataFrameRows, cols=:)
names(df::DataFrameColumns, cols=:)
names(df::GroupKey)
Return a freshly allocated `Vector{String}` of names of columns contained in `df`.
If `cols` is passed then restrict returned column names to those matching the
selector (this is useful in particular with regular expressions, `Cols`, `Not`, and `Between`).
`cols` can be:
* any column selector ($COLUMNINDEX_STR; $MULTICOLUMNINDEX_STR); these column
selectors are documented in the [General rules](@ref) section of the [Indexing](@ref)
part of the DataFrames.jl manual
* a `Type`, in which case names of columns whose `eltype` is a subtype of `T`
are returned
* a `Function` predicate taking the column name as a string and returning `true`
for columns that should be kept
See also [`propertynames`](@ref) which returns a `Vector{Symbol}`
(except for `GroupedDataFrame` in which case use `Symbol.(names(df))`).
# Examples
```jldoctest
julia> df = DataFrame(x1=[1, missing, missing], x2=[3, 2, 4], x3=[3, missing, 2], x4=Union{Int, Missing}[2, 4, 4])
3×4 DataFrame
Row │ x1 x2 x3 x4
│ Int64? Int64 Int64? Int64?
─────┼─────────────────────────────────
1 │ 1 3 3 2
2 │ missing 2 missing 4
3 │ missing 4 2 4
julia> names(df)
4-element Vector{String}:
"x1"
"x2"
"x3"
"x4"
julia> names(df, Int) # pick columns whose element type is Int
1-element Vector{String}:
"x2"
julia> names(df, x -> x[end] == '2') # pick columns for which last character in their name is '2'
1-element Vector{String}:
"x2"
julia> fun(col) = sum(skipmissing(col)) >= 10
fun (generic function with 1 method)
julia> names(df, fun.(eachcol(df))) # pick columns for which sum of their elements is at least 10
1-element Vector{String}:
"x4"
julia> names(df, eltype.(eachcol(df)) .>: Missing) # pick columns that allow missing values
3-element Vector{String}:
"x1"
"x3"
"x4"
julia> names(df, any.(ismissing, eachcol(df))) # pick columns that contain missing values
2-element Vector{String}:
"x1"
"x3"
```
"""
Base.names(df::AbstractDataFrame, cols::Colon=:) = names(index(df))
function Base.names(df::AbstractDataFrame, cols)
nms = _names(index(df))
idx = index(df)[cols]
idxs = idx isa Int ? (idx:idx) : idx
return [String(nms[i]) for i in idxs]
end
Base.names(df::AbstractDataFrame, T::Type) =
[String(n) for (n, c) in pairs(eachcol(df)) if eltype(c) <: T]
Base.names(df::AbstractDataFrame, fun::Function) = filter!(fun, names(df))
# _names returns Vector{Symbol} without copying
_names(df::AbstractDataFrame) = _names(index(df))
# separate methods are needed due to dispatch ambiguity
Compat.hasproperty(df::AbstractDataFrame, s::Symbol) = haskey(index(df), s)
Compat.hasproperty(df::AbstractDataFrame, s::AbstractString) = haskey(index(df), s)
"""
rename!(df::AbstractDataFrame, vals::AbstractVector{Symbol};
makeunique::Bool=false)
rename!(df::AbstractDataFrame, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false)
rename!(df::AbstractDataFrame, (from => to)::Pair...)
rename!(df::AbstractDataFrame, d::AbstractDict)
rename!(df::AbstractDataFrame, d::AbstractVector{<:Pair})
rename!(f::Function, df::AbstractDataFrame; cols=All())
Rename columns of `df` in-place.
Each name is changed at most once. Permutation of names is allowed.
# Arguments
- `df` : the `AbstractDataFrame`
- `d` : an `AbstractDict` or an `AbstractVector` of `Pair`s that maps
the original names or column numbers to new names
- `f` : a function which for each column selected by the `cols` keyword argument
takes the old name as a `String`
and returns the new name that gets converted to a `Symbol`; the `cols`
column selector can be any value accepted as column selector by the `names` function
- `vals` : new column names as a vector of `Symbol`s or `AbstractString`s
of the same length as the number of columns in `df`
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found; if `true`, duplicate names will be suffixed
with `_i` (`i` starting at 1 for the first duplicate).
If pairs are passed to `rename!` (as positional arguments or in a dictionary or
a vector) then:
* `from` value can be a `Symbol`, an `AbstractString` or an `Integer`;
* `to` value can be a `Symbol` or an `AbstractString`.
Mixing symbols and strings in `to` and `from` is not allowed.
$METADATA_FIXED
Metadata having other styles is dropped (from parent data frame when `df` is a `SubDataFrame`).
Column-level `:note`-style metadata is considered to be attached to column number:
when a column is renamed, its `:note`-style metadata becomes associated to its new name.
See also: [`rename`](@ref)
# Examples
```jldoctest
julia> df = DataFrame(i=1, x=2, y=3)
1×3 DataFrame
Row │ i x y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename!(df, Dict(:i => "A", :x => "X"))
1×3 DataFrame
Row │ A X y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename!(df, [:a, :b, :c])
1×3 DataFrame
Row │ a b c
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename!(df, [:a, :b, :a])
ERROR: ArgumentError: Duplicate variable names: :a. Pass makeunique=true to make them unique using a suffix automatically.
julia> rename!(df, [:a, :b, :a], makeunique=true)
1×3 DataFrame
Row │ a b a_1
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename!(uppercase, df)
1×3 DataFrame
Row │ A B A_1
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename!(lowercase, df, cols=contains('A'))
1×3 DataFrame
Row │ a B a_1
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
```
"""
function rename!(df::AbstractDataFrame, vals::AbstractVector{Symbol};
makeunique::Bool=false)
rename!(index(df), vals, makeunique=makeunique)
# renaming columns of SubDataFrame has to clean non-note metadata in its parent
_drop_all_nonnote_metadata!(parent(df))
return df
end
function rename!(df::AbstractDataFrame, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false)
rename!(index(df), Symbol.(vals), makeunique=makeunique)
# renaming columns of SubDataFrame has to clean non-note metadata in its parent
_drop_all_nonnote_metadata!(parent(df))
return df
end
function rename!(df::AbstractDataFrame, args::AbstractVector{Pair{Symbol, Symbol}})
rename!(index(df), args)
# renaming columns of SubDataFrame has to clean non-note metadata in its parent
_drop_all_nonnote_metadata!(parent(df))
return df
end
function rename!(df::AbstractDataFrame,
args::Union{AbstractVector{<:Pair{Symbol, <:AbstractString}},
AbstractVector{<:Pair{<:AbstractString, Symbol}},
AbstractVector{<:Pair{<:AbstractString, <:AbstractString}},
AbstractDict{Symbol, Symbol},
AbstractDict{Symbol, <:AbstractString},
AbstractDict{<:AbstractString, Symbol},
AbstractDict{<:AbstractString, <:AbstractString}})
rename!(index(df), [Symbol(from) => Symbol(to) for (from, to) in args])
# renaming columns of SubDataFrame has to clean non-note metadata in its parent
_drop_all_nonnote_metadata!(parent(df))
return df
end
function rename!(df::AbstractDataFrame,
args::Union{AbstractVector{<:Pair{<:Integer, <:AbstractString}},
AbstractVector{<:Pair{<:Integer, Symbol}},
AbstractDict{<:Integer, <:AbstractString},
AbstractDict{<:Integer, Symbol}})
rename!(index(df), [_names(df)[from] => Symbol(to) for (from, to) in args])
# renaming columns of SubDataFrame has to clean non-note metadata in its parent
_drop_all_nonnote_metadata!(parent(df))
return df
end
# needed because of dispatch ambiguity
function rename!(df::AbstractDataFrame)
_drop_all_nonnote_metadata!(parent(df))
return df
end
rename!(df::AbstractDataFrame, args::Pair...) = rename!(df, collect(args))
rename!(f::Function, df::AbstractDataFrame; cols=All()) =
rename!(df, [n => Symbol(f(n)) for n in names(df, cols)])
"""
rename(df::AbstractDataFrame, vals::AbstractVector{Symbol};
makeunique::Bool=false)
rename(df::AbstractDataFrame, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false)
rename(df::AbstractDataFrame, (from => to)::Pair...)
rename(df::AbstractDataFrame, d::AbstractDict)
rename(df::AbstractDataFrame, d::AbstractVector{<:Pair})
rename(f::Function, df::AbstractDataFrame; cols=All())
Create a new data frame that is a copy of `df` with changed column names.
Each name is changed at most once. Permutation of names is allowed.
# Arguments
- `df` : the `AbstractDataFrame`; if it is a `SubDataFrame` then renaming is
only allowed if it was created using `:` as a column selector.
- `d` : an `AbstractDict` or an `AbstractVector` of `Pair`s that maps
the original names or column numbers to new names
- `f` : a function which for each column selected by the `cols` keyword argument
takes the old name as a `String`
and returns the new name that gets converted to a `Symbol`; the `cols`
column selector can be any value accepted as column selector by the `names` function
- `vals` : new column names as a vector of `Symbol`s or `AbstractString`s
of the same length as the number of columns in `df`
- `makeunique` : if `false` (the default), an error will be raised
if duplicate names are found; if `true`, duplicate names will be suffixed
with `_i` (`i` starting at 1 for the first duplicate).
If pairs are passed to `rename` (as positional arguments or in a dictionary or
a vector) then:
* `from` value can be a `Symbol`, an `AbstractString` or an `Integer`;
* `to` value can be a `Symbol` or an `AbstractString`.
Mixing symbols and strings in `to` and `from` is not allowed.
$METADATA_FIXED
Column-level `:note`-style metadata is considered to be attached to column number:
when a column is renamed, its `:note`-style metadata becomes associated to its
new name.
See also: [`rename!`](@ref)
# Examples
```jldoctest
julia> df = DataFrame(i=1, x=2, y=3)
1×3 DataFrame
Row │ i x y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename(df, [:a, :b, :c])
1×3 DataFrame
Row │ a b c
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename(df, :i => "A", :x => "X")
1×3 DataFrame
Row │ A X y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename(df, :x => :y, :y => :x)
1×3 DataFrame
Row │ i y x
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename(df, [1 => :A, 2 => :X])
1×3 DataFrame
Row │ A X y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename(df, Dict("i" => "A", "x" => "X"))
1×3 DataFrame
Row │ A X y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename(uppercase, df)
1×3 DataFrame
Row │ I X Y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
julia> rename(uppercase, df, cols=contains('x'))
1×3 DataFrame
Row │ i X y
│ Int64 Int64 Int64
─────┼─────────────────────
1 │ 1 2 3
```
"""
rename(df::AbstractDataFrame, vals::AbstractVector{Symbol};
makeunique::Bool=false) = rename!(copy(df), vals, makeunique=makeunique)
rename(df::AbstractDataFrame, vals::AbstractVector{<:AbstractString};
makeunique::Bool=false) = rename!(copy(df), vals, makeunique=makeunique)
rename(df::AbstractDataFrame, args...) = rename!(copy(df), args...)
rename(f::Function, df::AbstractDataFrame; cols=All()) = rename!(f, copy(df); cols=cols)
"""
size(df::AbstractDataFrame[, dim])
Return a tuple containing the number of rows and columns of `df`.
Optionally a dimension `dim` can be specified, where `1` corresponds to rows
and `2` corresponds to columns.
See also: [`nrow`](@ref), [`ncol`](@ref)
# Examples
```jldoctest
julia> df = DataFrame(a=1:3, b='a':'c');
julia> size(df)
(3, 2)
julia> size(df, 1)
3
```
"""
Base.size(df::AbstractDataFrame) = (nrow(df), ncol(df))
function Base.size(df::AbstractDataFrame, i::Integer)
if i == 1
nrow(df)
elseif i == 2
ncol(df)
else
throw(ArgumentError("DataFrames only have two dimensions"))
end
end
"""
ncol(df::AbstractDataFrame)
Return the number of columns in an `AbstractDataFrame` `df`.
See also [`nrow`](@ref), [`size`](@ref).
# Examples
```jldoctest
julia> df = DataFrame(i=1:10, x=rand(10), y=rand(["a", "b", "c"], 10));
julia> ncol(df)
3
```
"""
ncol(df::AbstractDataFrame) = length(index(df))
"""
isempty(df::AbstractDataFrame)
Return `true` if data frame `df` has zero rows, and `false` otherwise.
"""
Base.isempty(df::AbstractDataFrame) = nrow(df) == 0
Base.axes(df::AbstractDataFrame, i::Integer) = Base.OneTo(size(df, i))
"""
ndims(::AbstractDataFrame)
ndims(::Type{<:AbstractDataFrame})
Return the number of dimensions of a data frame, which is always `2`.
"""
Base.ndims(::AbstractDataFrame) = 2
Base.ndims(::Type{<:AbstractDataFrame}) = 2
# separate methods are needed due to dispatch ambiguity
Base.getproperty(df::AbstractDataFrame, col_ind::Symbol) = df[!, col_ind]
Base.getproperty(df::AbstractDataFrame, col_ind::AbstractString) = df[!, col_ind]
# Private fields are never exposed since they can conflict with column names
"""
propertynames(df::AbstractDataFrame)
Return a freshly allocated `Vector{Symbol}` of names of columns contained in `df`.
"""
Base.propertynames(df::AbstractDataFrame, private::Bool=false) = copy(_names(df))
##############################################################################
##
## Similar
##
##############################################################################
"""
similar(df::AbstractDataFrame, rows::Integer=nrow(df))
Create a new `DataFrame` with the same column names and column element types
as `df`. An optional second argument can be provided to request a number of rows
that is different than the number of rows present in `df`.
$METADATA_FIXED
"""
function Base.similar(df::AbstractDataFrame, rows::Integer = size(df, 1))
rows < 0 && throw(ArgumentError("the number of rows must be non-negative"))
out_df = DataFrame(AbstractVector[similar(x, rows) for x in eachcol(df)],
copy(index(df)), copycols=false)
_copy_all_note_metadata!(out_df, df)
return out_df
end
"""
empty(df::AbstractDataFrame)
Create a new `DataFrame` with the same column names and column element types
as `df` but with zero rows.
$METADATA_FIXED
"""
Base.empty(df::AbstractDataFrame) = similar(df, 0)
function Base.:(==)(df1::AbstractDataFrame, df2::AbstractDataFrame)
size(df1, 2) == size(df2, 2) || return false
isequal(index(df1), index(df2)) || return false
eq = true
for idx in 1:size(df1, 2)
coleq = df1[!, idx] == df2[!, idx]
# coleq could be missing
isequal(coleq, false) && return false
eq &= coleq
end
return eq
end
function Base.isequal(df1::AbstractDataFrame, df2::AbstractDataFrame)
size(df1, 2) == size(df2, 2) || return false
isequal(index(df1), index(df2)) || return false
for idx in 1:size(df1, 2)
isequal(df1[!, idx], df2[!, idx]) || return false
end
return true
end
"""
isapprox(df1::AbstractDataFrame, df2::AbstractDataFrame;
rtol::Real=atol>0 ? 0 : √eps, atol::Real=0,
nans::Bool=false, norm::Function=norm)
Inexact equality comparison. `df1` and `df2` must have the same size and column names.
Return `true` if `isapprox` with given keyword arguments
applied to all pairs of columns stored in `df1` and `df2` returns `true`.
"""
function Base.isapprox(df1::AbstractDataFrame, df2::AbstractDataFrame;
atol::Real=0, rtol::Real=atol>0 ? 0 : √eps(),
nans::Bool=false, norm::Function=norm)
if size(df1) != size(df2)
throw(DimensionMismatch("dimensions must match: a has dims " *
"$(size(df1)), b has dims $(size(df2))"))
end
if !isequal(index(df1), index(df2))
throw(ArgumentError("column names of passed data frames do not match"))
end
return all(isapprox.(eachcol(df1), eachcol(df2), atol=atol, rtol=rtol, nans=nans, norm=norm))
end
"""
only(df::AbstractDataFrame)
If `df` has a single row return it as a `DataFrameRow`; otherwise throw `ArgumentError`.
$METADATA_FIXED
"""
function Base.only(df::AbstractDataFrame)
n = nrow(df)
n != 1 && throw(ArgumentError("data frame must contain exactly 1 row, got $n"))
return df[1, :]
end
"""
first(df::AbstractDataFrame)
Get the first row of `df` as a `DataFrameRow`.
$METADATA_FIXED
"""
Base.first(df::AbstractDataFrame) = df[1, :]
"""
first(df::AbstractDataFrame, n::Integer; view::Bool=false)
Get a data frame with the `n` first rows of `df`.
Get all rows if `n` is greater than the number of rows in `df`.
Error if `n` is negative.
If `view=false` a freshly allocated `DataFrame` is returned.
If `view=true` then a `SubDataFrame` view into `df` is returned.
$METADATA_FIXED
"""
@inline function Base.first(df::AbstractDataFrame, n::Integer; view::Bool=false)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
r = min(n, nrow(df))
return view ? Base.view(df, 1:r, :) : df[1:r, :]
end
"""
last(df::AbstractDataFrame)
Get the last row of `df` as a `DataFrameRow`.
$METADATA_FIXED
"""
Base.last(df::AbstractDataFrame) = df[nrow(df), :]
"""
last(df::AbstractDataFrame, n::Integer; view::Bool=false)
Get a data frame with the `n` last rows of `df`.
Get all rows if `n` is greater than the number of rows in `df`.
Error if `n` is negative.
If `view=false` a freshly allocated `DataFrame` is returned.
If `view=true` then a `SubDataFrame` view into `df` is returned.
$METADATA_FIXED
"""
@inline function Base.last(df::AbstractDataFrame, n::Integer; view::Bool=false)
n < 0 && throw(ArgumentError("Number of elements must be nonnegative"))
r = max(1, nrow(df) - n + 1)
return view ? Base.view(df, r:nrow(df), :) : df[r:nrow(df), :]
end
"""
describe(df::AbstractDataFrame; cols=:)
describe(df::AbstractDataFrame, stats::Union{Symbol, Pair}...; cols=:)
Return descriptive statistics for a data frame as a new `DataFrame`
where each row represents a variable and each column a summary statistic.
# Arguments
- `df` : the `AbstractDataFrame`
- `stats::Union{Symbol, Pair}...` : the summary statistics to report.
Arguments can be:
- A symbol from the list `:mean`, `:std`, `:min`, `:q25`,
`:median`, `:q75`, `:max`, `:sum`, `:eltype`, `:nunique`, `:nuniqueall`, `:first`,
`:last`, `:nnonmissing`, and `:nmissing`. The default statistics used are
`:mean`, `:min`, `:median`, `:max`, `:nmissing`, and `:eltype`.
- `:detailed` as the only `Symbol` argument to return all statistics
except `:first`, `:last`, `:sum`, `:nuniqueall`, and `:nnonmissing`.
- `:all` as the only `Symbol` argument to return all statistics.
- A `function => name` pair where `name` is a `Symbol` or string. This will
create a column of summary statistics with the provided name.
- `cols` : a keyword argument allowing to select only a subset or transformation
of columns from `df` to describe. Can be any column selector or transformation
accepted by [`select`](@ref).
# Details
For `Real` columns, compute the mean, standard deviation, minimum, first
quantile, median, third quantile, and maximum. If a column does not derive from
`Real`, `describe` will attempt to calculate all statistics, using `nothing` as
a fall-back in the case of an error.
When `stats` contains `:nunique`, `describe` will report the
number of unique values in a column. If a column's base type derives from `Real`,
`:nunique` will return `nothing`s. Use `:nuniqueall` to report the number of
unique values in all columns.
Missing values are filtered in the calculation of all statistics, however the
column `:nmissing` will report the number of missing values of that variable
and `:nnonmissing` the number of non-missing values.
If custom functions are provided, they are called repeatedly with the vector
corresponding to each column as the only argument. For columns allowing for
missing values, the vector is wrapped in a call to `skipmissing`: custom
functions must therefore support such objects (and not only vectors), and cannot
access missing values.
Metadata: this function drops all metadata.
# Examples
```jldoctest
julia> df = DataFrame(i=1:10, x=0.1:0.1:1.0, y='a':'j');
julia> describe(df)
3×7 DataFrame
Row │ variable mean min median max nmissing eltype
│ Symbol Union… Any Union… Any Int64 DataType
─────┼────────────────────────────────────────────────────────
1 │ i 5.5 1 5.5 10 0 Int64
2 │ x 0.55 0.1 0.55 1.0 0 Float64
3 │ y a j 0 Char
julia> describe(df, :min, :max)
3×3 DataFrame
Row │ variable min max
│ Symbol Any Any
─────┼────────────────────
1 │ i 1 10
2 │ x 0.1 1.0
3 │ y a j
julia> describe(df, :min, sum => :sum)
3×3 DataFrame
Row │ variable min sum
│ Symbol Any Union…
─────┼───────────────────────
1 │ i 1 55
2 │ x 0.1 5.5
3 │ y a
julia> describe(df, :min, sum => :sum, cols=:x)
1×3 DataFrame
Row │ variable min sum
│ Symbol Float64 Float64
─────┼────────────────────────────
1 │ x 0.1 5.5
```
"""
DataAPI.describe(df::AbstractDataFrame,
stats::Union{Symbol, Pair{<:Base.Callable, <:SymbolOrString}}...;
cols=:) =
_describe(_try_select_no_copy(df, cols), Any[s for s in stats])
DataAPI.describe(df::AbstractDataFrame; cols=:) =
_describe(_try_select_no_copy(df, cols),
Any[:mean, :min, :median, :max, :nmissing, :eltype])
function _describe(df::AbstractDataFrame, stats::AbstractVector)
predefined_funs = Symbol[s for s in stats if s isa Symbol]
allowed_fields = [:mean, :std, :min, :q25, :median, :q75, :max, :sum,
:nunique, :nuniqueall, :nmissing, :nnonmissing,
:first, :last, :eltype]
if predefined_funs == [:all]
predefined_funs = allowed_fields
i = findfirst(s -> s == :all, stats)
splice!(stats, i, allowed_fields) # insert in the stats vector to get a good order
elseif predefined_funs == [:detailed]
predefined_funs = [:mean, :std, :min, :q25, :median, :q75,
:max, :nunique, :nmissing, :eltype]
i = findfirst(s -> s == :detailed, stats)
splice!(stats, i, predefined_funs) # insert in the stats vector to get a good order
elseif :all in predefined_funs || :detailed in predefined_funs
throw(ArgumentError("`:all` and `:detailed` must be the only `Symbol` argument."))
elseif !issubset(predefined_funs, allowed_fields)
not_allowed = join(setdiff(predefined_funs, allowed_fields), ", :")
allowed_msg = "\nAllowed fields are: :" * join(allowed_fields, ", :")
throw(ArgumentError(":$not_allowed not allowed." * allowed_msg))
end
custom_funs = Any[s[1] => Symbol(s[2]) for s in stats if s isa Pair]
ordered_names = [s isa Symbol ? s : Symbol(last(s)) for s in stats]
if !allunique(ordered_names)
df_ord_names = DataFrame(ordered_names = ordered_names)
duplicate_names = unique(ordered_names[nonunique(df_ord_names)])
throw(ArgumentError("Duplicate names not allowed. Duplicated value(s) are: " *
":$(join(duplicate_names, ", "))"))
end
# Put the summary stats into the return data frame
data = DataFrame()
data.variable = propertynames(df)
# An array of Dicts for summary statistics
col_stats_dicts = map(eachcol(df)) do col
if eltype(col) >: Missing
t = skipmissing(col)
d = get_stats(t, predefined_funs)
get_stats!(d, t, custom_funs)
else
d = get_stats(col, predefined_funs)
get_stats!(d, col, custom_funs)
end
if :nmissing in predefined_funs
d[:nmissing] = count(ismissing, col)
end
if :nnonmissing in predefined_funs
d[:nnonmissing] = count(!ismissing, col)
end
if :first in predefined_funs
d[:first] = isempty(col) ? nothing : first(col)
end
if :last in predefined_funs
d[:last] = isempty(col) ? nothing : last(col)
end
if :eltype in predefined_funs
d[:eltype] = eltype(col)
end
return d
end
for stat in ordered_names
# for each statistic, loop through the columns array to find values
# letting the comprehension choose the appropriate type
data[!, stat] = [d[stat] for d in col_stats_dicts]
end
return data
end
# Compute summary statistics
# use a dict because we don't know which measures the user wants
# Outside of the `describe` function due to something with 0.7
function get_stats(@nospecialize(col::Union{AbstractVector, Base.SkipMissing}),
stats::AbstractVector{Symbol})
d = Dict{Symbol, Any}()
if :q25 in stats || :median in stats || :q75 in stats
# types that do not support basic arithmetic (like strings) will only fail
# after sorting the data, so check this beforehand to fail early
T = eltype(col)
if isconcretetype(T) && !hasmethod(-, Tuple{T, T})
d[:q25] = d[:median] = d[:q75] = nothing
else
mcol = Base.copymutable(col)
if :q25 in stats
d[:q25] = try quantile!(mcol, 0.25) catch; nothing; end
end
if :median in stats
d[:median] = try quantile!(mcol, 0.50) catch; nothing; end
end
if :q75 in stats
d[:q75] = try quantile!(mcol, 0.75) catch; nothing; end
end
end
end
if :min in stats || :max in stats
ex = try extrema(col) catch; (nothing, nothing) end
d[:min] = ex[1]
d[:max] = ex[2]
end
if :mean in stats || :std in stats
m = try mean(col) catch end
# we can add non-necessary things to d, because we choose what we need
# in the main function
d[:mean] = m
if :std in stats
d[:std] = try std(col, mean = m) catch end
end
end
if :nunique in stats
if eltype(col) <: Real
d[:nunique] = nothing
else
d[:nunique] = try length(Set(col)) catch end
end
end
if :nuniqueall in stats
d[:nuniqueall] = try length(Set(col)) catch end
end
if :sum in stats
d[:sum] = try sum(col) catch end
end
return d
end
function get_stats!(d::Dict, @nospecialize(col::Union{AbstractVector, Base.SkipMissing}),
stats::Vector{Any})
for stat in stats
d[stat[2]] = try stat[1](col) catch end
end
end
"""
completecases(df::AbstractDataFrame, cols=:)
Return a Boolean vector with `true` entries indicating rows without missing values
(complete cases) in data frame `df`.
If `cols` is provided, only missing values in the corresponding columns are considered.
`cols` can be any column selector ($COLUMNINDEX_STR; $MULTICOLUMNINDEX_STR)
that returns at least one column if `df` has at least one column.
See also: [`dropmissing`](@ref) and [`dropmissing!`](@ref).
Use `findall(completecases(df))` to get the indices of the rows.
# Examples
```jldoctest
julia> df = DataFrame(i=1:5,
x=[missing, 4, missing, 2, 1],
y=[missing, missing, "c", "d", "e"])
5×3 DataFrame
Row │ i x y
│ Int64 Int64? String?
─────┼─────────────────────────
1 │ 1 missing missing
2 │ 2 4 missing
3 │ 3 missing c
4 │ 4 2 d
5 │ 5 1 e
julia> completecases(df)
5-element BitVector:
0
0
0
1
1
julia> completecases(df, :x)
5-element BitVector:
0
1
0
1
1
julia> completecases(df, [:x, :y])
5-element BitVector:
0
0
0
1
1
```
"""
function completecases(df::AbstractDataFrame, cols::MultiColumnIndex=:)
colsidx = index(df)[cols]
length(colsidx) == 1 && return completecases(df, only(colsidx))
if ncol(df) > 0 && isempty(colsidx)
throw(ArgumentError("finding complete cases in data frame when " *
"`cols` selects no columns is not allowed"))
end
res = trues(size(df, 1))
ncol(df) == 0 && return res
aux = BitVector(undef, size(df, 1))
for i in colsidx
v = df[!, i]
if Missing <: eltype(v)
# Disable fused broadcasting as it happens to be much slower
aux .= .!ismissing.(v)
res .&= aux
end
end
return res
end
function completecases(df::AbstractDataFrame, col::ColumnIndex)
v = df[!, col]
if Missing <: eltype(v)
res = BitVector(undef, size(df, 1))
res .= .!ismissing.(v)
return res
else
return trues(size(df, 1))
end
end
"""
dropmissing(df::AbstractDataFrame, cols=:; view::Bool=false, disallowmissing::Bool=!view)
Return a data frame excluding rows with missing values in `df`.
If `cols` is provided, only missing values in the corresponding columns are considered.
`cols` can be any column selector ($COLUMNINDEX_STR; $MULTICOLUMNINDEX_STR).
If `view=false` a freshly allocated `DataFrame` is returned.
If `view=true` then a `SubDataFrame` view into `df` is returned. In this case
`disallowmissing` must be `false`.
If `disallowmissing` is `true` (the default when `view` is `false`)
then columns specified in `cols` will be converted so as not to allow for missing
values using [`disallowmissing!`](@ref).
See also: [`completecases`](@ref) and [`dropmissing!`](@ref).
$METADATA_FIXED
# Examples
```jldoctest
julia> df = DataFrame(i=1:5,
x=[missing, 4, missing, 2, 1],
y=[missing, missing, "c", "d", "e"])
5×3 DataFrame
Row │ i x y
│ Int64 Int64? String?
─────┼─────────────────────────
1 │ 1 missing missing
2 │ 2 4 missing
3 │ 3 missing c
4 │ 4 2 d
5 │ 5 1 e
julia> dropmissing(df)
2×3 DataFrame
Row │ i x y
│ Int64 Int64 String
─────┼──────────────────────
1 │ 4 2 d
2 │ 5 1 e
julia> dropmissing(df, disallowmissing=false)
2×3 DataFrame
Row │ i x y
│ Int64 Int64? String?
─────┼────────────────────────
1 │ 4 2 d
2 │ 5 1 e
julia> dropmissing(df, :x)
3×3 DataFrame
Row │ i x y
│ Int64 Int64 String?
─────┼───────────────────────
1 │ 2 4 missing
2 │ 4 2 d
3 │ 5 1 e
julia> dropmissing(df, [:x, :y])