Skip to content

Commit

Permalink
Allow permutaion of names in rename!
Browse files Browse the repository at this point in the history
Signed-off-by: lizz <lizz@sensetime.com>
  • Loading branch information
innerlee committed Oct 5, 2019
1 parent 8bec53d commit a76f0d2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/other/index.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,26 @@ function names!(x::Index, nms::Vector{Symbol}; makeunique::Bool=false)
end

function rename!(x::Index, nms)
xbackup = copy(x)
toholder = Dict()
for (from, to) in nms
from == to && continue # No change, nothing to do
if haskey(x, to)
if haskey(toholder, to)
copy!(x.lookup, xbackup.lookup)
x.names .= xbackup.names
error("Tried renaming $from to $to, when $to already exists in the Index.")
end
x.lookup[to] = col = pop!(x.lookup, from)
if haskey(x, to)
toholder[to] = x.lookup[to]
end
x.lookup[to] = col = haskey(toholder, from) ? pop!(toholder, from) : pop!(x.lookup, from)
x.names[col] = to
end
if !isempty(toholder)
copy!(x.lookup, xbackup.lookup)
x.names .= xbackup.names
error("Tried renaming to $(join(keys(toholder), ", ")), when it already exists in the Index.")
end
return x
end

Expand Down
10 changes: 10 additions & 0 deletions test/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,16 @@ end
@test names(df) == [:A_4, :B_4]
@test rename!(x->Symbol(lowercase(string(x))), df) === df
@test names(df) == [:a_4, :b_4]

df = DataFrame(A = 1:3, B = 'A':'C', C = [:x, :y, :z])
@test rename!(df, :A => :B, :B => :A) === df
@test names(df) == [:B, :A, :C]
@test rename!(df, :A => :B, :B => :A, :C => :D) === df
@test names(df) == [:A, :B, :D]
@test rename!(df, :A => :B, :B => :C, :D => :A) === df
@test names(df) == [:B, :C, :A]
@test rename!(df, :A => :B, :B => :C, :C => :A) === df
@test names(df) == [:C, :A, :B]
end

@testset "size" begin
Expand Down

0 comments on commit a76f0d2

Please sign in to comment.