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

check for data frame corruption in delete! #2690

Merged
merged 4 commits into from
Apr 7, 2021
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
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
selected as a property (e.g. `df.col .= 1`) is allowed when column does not
exist and it allocates a fresh column
([#2655](https://github.com/JuliaData/DataFrames.jl/pull/2655))
* `delete!` now correctly handles the case when columns of a data frame are aliased
([#2690](https://github.com/JuliaData/DataFrames.jl/pull/2690))

## Deprecated

Expand Down
31 changes: 27 additions & 4 deletions src/dataframe/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -966,23 +966,46 @@ function Base.delete!(df::DataFrame, inds)
if !isempty(inds) && size(df, 2) == 0
throw(BoundsError(df, (inds, :)))
end

# we require ind to be stored and unique like in Base
# otherwise an error will be thrown and the data frame will get corrupted
foreach(col -> deleteat!(col, inds), _columns(df))
return df
return _delete!_helper(df, inds)
end

function Base.delete!(df::DataFrame, inds::AbstractVector{Bool})
if length(inds) != size(df, 1)
throw(BoundsError(df, (inds, :)))
end
drop = findall(inds)
foreach(col -> deleteat!(col, drop), _columns(df))
return df
return _delete!_helper(df, drop)
end

Base.delete!(df::DataFrame, inds::Not) = delete!(df, axes(df, 1)[inds])

function _delete!_helper(df::DataFrame, drop)
cols = _columns(df)
isempty(cols) && return df

n = nrow(df)
col1 = cols[1]
deleteat!(col1, drop)
newn = length(col1)

for i in 2:length(cols)
col = cols[i]
if length(col) == n
deleteat!(col, drop)
end
end

for i in 1:length(cols)
# this should never happen, but we add it for safety
@assert length(cols[i]) == newn corrupt_msg(df, i)
bkamins marked this conversation as resolved.
Show resolved Hide resolved
end

return df
end

"""
empty!(df::DataFrame)

Expand Down
7 changes: 7 additions & 0 deletions test/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,13 @@ end
@test delete!(df, v) == DataFrame(x=[2, 3])
@test x == [2, 3]
end

for inds in (1, [1], [true, false])
df = DataFrame(x1=[1, 2])
df.x2 = df.x1
@test delete!(df, inds) === df
@test df == DataFrame(x1=[2], x2=[2])
end
end

@testset "describe" begin
Expand Down