Snowy
1
Hi all,
I’m sure this is pretty simple but it’s tripping me up.
Say I have a dictionary as such:
using DataFrames
using Dates
Dates_to_remember = Dict(:Birthday=> Set([
Date("2021-01-15"),
Date("1991-08-30"),
Date("1954-07-01")
]),
:Anniversary => Set([
Date("1997-01-25"),
Date("2017-09-30")
]))
How can I transform this so that the output looks like this?:
transformed_output = DataFrame(:Date=>["2021-01-15","1991-08-30","1954-07-01","1997-01-25","2017-09-30"],:Category=>["Birthday","Bithday","Birthday","Anniversary","Anniversary"])
I’ve tried using values() but that gets me the set. I can’t really figure out how to get the values within the set to put into the DF.
Thanks for your help!
Snowy
jules
2
This is one option:
julia> flatten(stack(DataFrame(Dates_to_remember), :), :value)
5×2 DataFrame
Row │ variable value
│ String Date
─────┼─────────────────────────
1 │ Anniversary 2017-09-30
2 │ Anniversary 1997-01-25
3 │ Birthday 1991-08-30
4 │ Birthday 2021-01-15
5 │ Birthday 1954-07-01
2 Likes
sgaure
3
Or more straightforward:
transformed_output = DataFrame()
for (k,v) in Dates_to_remember
for d in v
push!(transformed_output, (Date=d, Category=k))
end
end
Use string(d)
and string(k)
if you want strings.
1 Like
Snowy
4
These are great functions I didn’t know existed.
Thank you to you both!
I think the whole thing can be written as simply as:
DataFrame((Date=d, Category=k) for (k,v) in Dates_to_remember for d in v)
1 Like