Is there any built-in function to convert a matrix to a DataFrame with the structure of a second DataFrame ?
i.e. :
df = DataFrame(a = [1,2,3], b= ["a","b","c"])
# Option 1, types not promoted
dfnames = names(df)
m = [4 "d"; 5 "e"]
df2 = DataFrame(m,dfnames) # doesn't promote types
# Option 2, manual assignment
df2 = similar(df,size(m,1))
[df2[:,cidx] = m[:,cidx] for cidx in axes(df2,2)]
df2 # fine
I have scrolled through the doc for the DataFrame constructor and didn’t find anything.. it would be nice to have something like:
df = DataFrame(matrix,otherdf)
Seems a pretty niche use case, and fundamentally the matrix just doesn’t store the type information you’re after, but if if you just want to save some typing you can do
julia> df2 = identity.(DataFrame(m,dfnames))
2×2 DataFrame
Row │ a b
│ Int64 String
─────┼───────────────
1 │ 4 d
2 │ 5 e
1 Like
df2 = similar(df, size(m,1))
df2 .= m
#or
df2 = similar(df, size(m,1)).=m
1 Like
Another way:
df2 = copy(df[axes(m)...]) .= m
All answers are valid, but I still believe a DF constructor that explicitly differentiate between data and structure (that goes behind the column names) would be welcomed…