Last active
September 22, 2020 18:42
-
-
Save contradict/6c2a20879c38dd907d119a659bf3ca42 to your computer and use it in GitHub Desktop.
How to unstack multiple columns with Julia DataFrames.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### A Pluto.jl notebook ### | |
# v0.11.9 | |
using Markdown | |
using InteractiveUtils | |
# ╔═╡ d10371f6-e94c-11ea-0309-5788d6e340b3 | |
begin | |
using Pkg | |
Pkg.activate(".") | |
using DataFrames, Underscores | |
end | |
# ╔═╡ eaa10ed8-ea13-11ea-32c5-67b6ea3189ba | |
example_df = DataFrame(:Run=>[1, 1, 2, 2, 3, 3], | |
:Type=>["a", "b", "a", "b", "a", "b"], | |
:x1=>[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], | |
:x2=>[0.6, 0.5, 0.4, 0.3, 0.2, 0.1]) | |
# ╔═╡ 7e15e0f0-e988-11ea-06bf-1547cbce413f | |
desired_df = DataFrame(:Run=>[1, 2, 3], | |
:a_x1=>[0.1, 0.3, 0.5], | |
:b_x1=>[0.2, 0.4, 0.6], | |
:a_x2=>[0.6, 0.4, 0.2], | |
:b_x2=>[0.5, 0.3, 0.1]) | |
# ╔═╡ 19fabe14-e966-11ea-29bf-bf4757345e6b | |
@_ example_df |> | |
groupby(__, :Run) |> | |
combine(__, [("Type", v) => ((x, y) -> y[x .== t]) => t*"_"*v for v in ["x1", "x2"] for t in unique(example_df.Type)]) | |
# ╔═╡ bd6ff950-e98a-11ea-1d03-576ddfb22d12 | |
@_ example_df |> | |
[unstack(__, :Run, :Type, v, renamecols = x->x*"_"*v) for v in ["x1", "x2"]] |> | |
outerjoin(__..., on=:Run) | |
# ╔═╡ Cell order: | |
# ╠═d10371f6-e94c-11ea-0309-5788d6e340b3 | |
# ╠═eaa10ed8-ea13-11ea-32c5-67b6ea3189ba | |
# ╠═7e15e0f0-e988-11ea-06bf-1547cbce413f | |
# ╠═19fabe14-e966-11ea-29bf-bf4757345e6b | |
# ╠═bd6ff950-e98a-11ea-1d03-576ddfb22d12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment