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

Fix empty unstack on empty data frame #2842

Merged
merged 4 commits into from
Aug 24, 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
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@
integers in a small range.
([#2812](https://github.com/JuliaData/DataFrames.jl/pull/2812))

## Bug fixes

* fix a problem with `unstack` on empty data frame
([#2842](https://github.com/JuliaData/DataFrames.jl/issues/2842))

# DataFrames.jl v1.2.2 Patch Release Notes

## Bug fixes
Expand Down
5 changes: 3 additions & 2 deletions src/abstractdataframe/reshape.jl
Original file line number Diff line number Diff line change
Expand Up @@ -418,10 +418,11 @@ function _unstack(df::AbstractDataFrame, rowkeys::AbstractVector{Int},
mask_filled[row_id, col_id] = true
end

# note that Symbol.(renamecols.(colref_map)) must produce unique column names
# note that Symbol(renamecols(colref_map)) must produce unique column names
# and names between df1 and df2 must be unique
df1 = df[row_group_row_idxs, g_rowkey.cols]
df2 = DataFrame(unstacked_val, Symbol.(renamecols.(colref_map)), copycols=false)
df2 = DataFrame(unstacked_val, Symbol[Symbol(renamecols(x)) for x in colref_map],
copycols=false)

@assert length(col_group_row_idxs) == ncol(df2)
# avoid reordering when col_group_row_idxs was already ordered
Expand Down
8 changes: 8 additions & 0 deletions test/reshape.jl
Original file line number Diff line number Diff line change
Expand Up @@ -654,4 +654,12 @@ end
@test IndexStyle(DataFrames.StackedVector) == IndexLinear()
end

@testset "empty unstack" begin
df = DataFrame(a = [], b = [], c = [])
dfu = unstack(df, :b, :c)
@test isempty(dfu)
@test names(dfu) == ["a"]
@test dfu.a isa Vector{Any}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any particular reason to check this type?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For current and future safety I guess. I was surprised that:

julia> Symbol.(Any[])
Any[]

because I knew that:

julia> map(Symbol, Any[])
Symbol[]

so I thought it does not hurt to be extra careful with empty collections and add a test.

end

end # module