How to create a DataFrame with specific number of columns and rows and fill it with zeros?

Hi!
I’m trying to create a dataframe where the first column have certain number of rows named in the following way:

df = DataFrame("Names" => names(df_rowname)[2:end])

Now I want to add n number of columns to df with labels names names(df_colname), and fill all the cells with zeros (or another initialization value).
What is the best way to do it? I can use the first line I wrote here to create the dataframe with the first column, but I’m not sure how to add the rest of them.

Thank you!

DataFrames are best used to represent data which has several attributes with heterogenous types. It seems that you are going to create some sort of a Matrix with a common type to the data in the columns.

If this is the case, and the names of the rows and columns are important, consider using NamedArrays.jl instead of a DataFrame.

2 Likes

Try MWE:

using DataFrames

df_rowname = DataFrame([(a=1, b=2, c=3, d=4)])

df = DataFrame("Names" => names(df_rowname)[2:end])
foreach(x -> df[!, x] = zeros(nrow(df)), names(df_rowname))
df

Thanks both of you for the helpful insights!

Another option:

row_names = ["a","b","c","d"]
col_names = ["x","y","z"]
zeros_matrix = zeros(length(row_names), length(col_names))
base_df = DataFrame(zeros_matrix, col_names)
row_names_df = DataFrame(rows = row_names)
hcat(row_names_df, base_df)
1 Like

One more:

julia> DataFrame(:Names => [:a, :b, :c], ([:x, :y, :z] .=> 0.0)...)
3×4 DataFrame
 Row │ Names   x        y        z       
     │ Symbol  Float64  Float64  Float64 
─────┼───────────────────────────────────
   1 │ a           0.0      0.0      0.0
   2 │ b           0.0      0.0      0.0
   3 │ c           0.0      0.0      0.0

Or equivalently

DataFrame([:Names => [:a, :b, :c]; [:x, :y, :z] .=> 0.0])
2 Likes

If you want to add columns to an existing data frame you can also use insertcols! or transform!.

1 Like
insertcols!(describe(df_rowname)[2:end,1:1],(names(df_rowname).=>0)...)
2 Likes