Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add only #2449

Merged
merged 4 commits into from
Sep 24, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 VERSION >= v"1.4"
bkamins marked this conversation as resolved.
Show resolved Hide resolved
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