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

droplevels!(): more efficient implementation #359

Merged
merged 5 commits into from
Aug 17, 2021
Merged
Changes from 2 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
25 changes: 24 additions & 1 deletion src/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,30 @@ unique(A::CategoricalArray{T}) where {T} = _unique(T, A.refs, A.pool)
Drop levels which do not appear in categorical array `A` (so that they will no longer be
returned by [`levels`](@ref DataAPI.levels)).
"""
droplevels!(A::CategoricalArray) = levels!(A, intersect(levels(A), unique(A)))
function droplevels!(A::CategoricalArray)
arefs = refs(A)
nlevels = length(levels(A))
seen = fill(false, nlevels)
nseen = 0
@inbounds for ref in arefs
if (ref > 0) && !seen[ref]
seen[ref] = true
nseen += 1
(nseen == nlevels) && return A # all levels observed, nothing to drop
end
end
# recode refs to keep only the seen ones (optimized version of update_refs!())
newlv = 0
levelsmap = [s ? (newlv += 1) : 0 for s in seen]
@inbounds for i in eachindex(arefs)
if arefs[i] > 0
alyst marked this conversation as resolved.
Show resolved Hide resolved
arefs[i] = levelsmap[arefs[i]]
end
end
alyst marked this conversation as resolved.
Show resolved Hide resolved
# replace the pool
A.pool = typeof(pool(A))(@inbounds(levels(A)[seen]), isordered(A))
return A
end

"""
isordered(A::CategoricalArray)
Expand Down