Skip to content

Commit

Permalink
add only (#2449)
Browse files Browse the repository at this point in the history
  • Loading branch information
bkamins authored Sep 24, 2020
1 parent bf1cfbd commit 8ea2edf
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/src/lib/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ filter
filter!
first
last
only
nonunique
unique
unique!
Expand Down
7 changes: 7 additions & 0 deletions src/DataFrames.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ if VERSION < v"1.2"
export hasproperty
end

if isdefined(Base, :only) # Introduced in 1.4.0
import Base.only
else
import Compat.only
export only
end

include("other/utils.jl")
include("other/index.jl")

Expand Down
10 changes: 10 additions & 0 deletions src/abstractdataframe/abstractdataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,16 @@ end
##
##############################################################################

"""
only(df::AbstractDataFrame)
If `df` has a single row return it as a `DataFrameRow`; otherwise throw `ArgumentError`.
"""
function only(df::AbstractDataFrame)
nrow(df) != 1 && throw(ArgumentError("data frame must contain exactly 1 row"))
return df[1, :]
end

"""
first(df::AbstractDataFrame)
Expand Down
7 changes: 6 additions & 1 deletion test/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,7 @@ end
@inferred ncol(df)
end

@testset "description" begin
@testset "first, last and only" begin
df = DataFrame(A = 1:10)

@test first(df) == df[1, :]
Expand All @@ -1063,6 +1063,11 @@ end
@test first(df, 1) == DataFrame(A = 1)
@test last(df, 6) == DataFrame(A = 5:10)
@test last(df, 1) == DataFrame(A = 10)

@test_throws ArgumentError only(df)
@test_throws ArgumentError only(DataFrame())
df = DataFrame(a=1, b=2)
@test only(df) === df[1, :]
end

@testset "column conversions" begin
Expand Down

0 comments on commit 8ea2edf

Please sign in to comment.