I need to construct a DataFrame similar to:
String, String, String, ...
:cod_1, :cod_2, :cod_3, cod_...
where the number of String is huge. So, by supposing that this number is N, how to construct df with a loop similar to:
for k in 1:N String
for k in 1:N string("cod_",k)
Of, course, the previous code does not work. Could you tell me the right way for such a code ? Thanks !
Please see PSA: how to quote code with backticks (and update your post accordingly).
I’m not sure, if I missed something, but this is valid code:
julia> n = 7
julia> DataFrame([String for k in 1:n],
[Symbol("cod_$k") for k in 1:n],
Thanks ! It works ! Nevertheless, how to use it when we need to have Date and String. More precisely, this bad code does not work:
DataFrame([Date, String for k in 1:2],
[:val_date, Symbol("cod_$k") for k in 1:2],
DataFrame([Date, String, String, ...],
[:val_date, :cod_1, :cod_2, ...],
I found a solution by using 2 dataframes and the join function:
df_2=DataFrame([String for k in 1:7],
[Symbol("cod_$k") for k in 1:7],
But it seems to me that it could be more simple. Is it the case ?
For passing the
vcat(Date, fill(String, 2)) # Example [Date, String, String]
You can use
vcat for the names as well.
Yes, and eventually think of using the broadcast feature for the column names.
julia> using DataFrames, Dates
julia> n = 7
julia> makecol(k) = Symbol("cod_", k)
makecol (generic function with 1 method)
julia> df = DataFrame([Date, fill(String, n)...],
For a more general way to do this, you can create an “empty” DataFrame with the schema that you want and then just
push! Dicts or Named Tuples to add observations to it. I have done this with fair amounts of success when the creation of the DataFrame is less trivial.