Skip to content

Commit

Permalink
make setindex! not create duplicate column names (#1373)
Browse files Browse the repository at this point in the history
  • Loading branch information
bkamins authored and ararslan committed Mar 4, 2018
1 parent e226a0f commit a2e8ea9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
20 changes: 11 additions & 9 deletions src/dataframe/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -312,13 +312,15 @@ Base.getindex(df::DataFrame, ::Colon, ::Colon) = copy(df)
##
##############################################################################

isnextcol(df::DataFrame, col_ind::Symbol) = true
function isnextcol(df::DataFrame, col_ind::Real)
return ncol(df) + 1 == Int(col_ind)
end

function nextcolname(df::DataFrame)
return Symbol(string("x", ncol(df) + 1))
col = Symbol(string("x", ncol(df) + 1))
haskey(index(df), col) || return col
i = 1
while true
col = Symbol(string("x", ncol(df) + 1, "_", i))
haskey(index(df), col) || return col
i += 1
end
end

# Will automatically add a new column if needed
Expand All @@ -327,7 +329,7 @@ function insert_single_column!(df::DataFrame,
col_ind::ColumnIndex)

if ncol(df) != 0 && nrow(df) != length(dv)
error("New columns must have the same length as old columns")
throw(ArgumentError("New columns must have the same length as old columns"))
end
if haskey(index(df), col_ind)
j = index(df)[col_ind]
Expand All @@ -337,11 +339,11 @@ function insert_single_column!(df::DataFrame,
push!(index(df), col_ind)
push!(df.columns, dv)
else
if isnextcol(df, col_ind)
if ncol(df) + 1 == Int(col_ind)
push!(index(df), nextcolname(df))
push!(df.columns, dv)
else
error("Cannot assign to non-existent column: $col_ind")
throw(ArgumentError("Cannot assign to non-existent column: $col_ind"))
end
end
end
Expand Down
13 changes: 11 additions & 2 deletions test/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ module TestDataFrame
#test_group("DataFrame assignment")
# Insert single column
x0 = x[Int[], :]
@test_throws ErrorException x0[:d] = [1]
@test_throws ErrorException x0[:d] = 1:3
@test_throws ArgumentError x0[:d] = [1]
@test_throws ArgumentError x0[:d] = 1:3

# Insert single value
x[:d] = 3
Expand Down Expand Up @@ -573,4 +573,13 @@ module TestDataFrame
e = @test_throws ArgumentError similar(df, -1)
@test e.value.msg == "the number of rows must be positive"
end

@testset "setindex! special cases" begin
df = DataFrame(rand(3,2), [:x3, :x3_1])
@test_throws ArgumentError df[3] = [1, 2]
@test_throws ArgumentError df[4] = [1, 2, 3]
df[3] = [1,2,3]
df[4] = [1,2,3]
@test names(df) == [:x3, :x3_1, :x3_2, :x4]
end
end

0 comments on commit a2e8ea9

Please sign in to comment.