Skip to content

Commit 8ea2edf

Browse files
authored
add only (#2449)
1 parent bf1cfbd commit 8ea2edf

File tree

4 files changed

+24
-1
lines changed

4 files changed

+24
-1
lines changed

docs/src/lib/functions.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ filter
9999
filter!
100100
first
101101
last
102+
only
102103
nonunique
103104
unique
104105
unique!

src/DataFrames.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,13 @@ if VERSION < v"1.2"
8080
export hasproperty
8181
end
8282

83+
if isdefined(Base, :only) # Introduced in 1.4.0
84+
import Base.only
85+
else
86+
import Compat.only
87+
export only
88+
end
89+
8390
include("other/utils.jl")
8491
include("other/index.jl")
8592

src/abstractdataframe/abstractdataframe.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,16 @@ end
434434
##
435435
##############################################################################
436436

437+
"""
438+
only(df::AbstractDataFrame)
439+
440+
If `df` has a single row return it as a `DataFrameRow`; otherwise throw `ArgumentError`.
441+
"""
442+
function only(df::AbstractDataFrame)
443+
nrow(df) != 1 && throw(ArgumentError("data frame must contain exactly 1 row"))
444+
return df[1, :]
445+
end
446+
437447
"""
438448
first(df::AbstractDataFrame)
439449

test/dataframe.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1051,7 +1051,7 @@ end
10511051
@inferred ncol(df)
10521052
end
10531053

1054-
@testset "description" begin
1054+
@testset "first, last and only" begin
10551055
df = DataFrame(A = 1:10)
10561056

10571057
@test first(df) == df[1, :]
@@ -1063,6 +1063,11 @@ end
10631063
@test first(df, 1) == DataFrame(A = 1)
10641064
@test last(df, 6) == DataFrame(A = 5:10)
10651065
@test last(df, 1) == DataFrame(A = 10)
1066+
1067+
@test_throws ArgumentError only(df)
1068+
@test_throws ArgumentError only(DataFrame())
1069+
df = DataFrame(a=1, b=2)
1070+
@test only(df) === df[1, :]
10661071
end
10671072

10681073
@testset "column conversions" begin

0 commit comments

Comments
 (0)