# How to initialize empty dataframe of specified size

**URL:** <https://discourse.julialang.org/t/how-to-initialize-empty-dataframe-of-specified-size/67421>\
**Category:** New to Julia\
**Tags:** dataframes\
**Created:** [August 31, 2021, 11:55am UTC](https://discourse.julialang.org/t/how-to-initialize-empty-dataframe-of-specified-size/67421 "2021-08-31T11:55:55Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)\
**Post date:** [August 31, 2021, 12:50pm UTC](https://discourse.julialang.org/t/how-to-initialize-empty-dataframe-of-specified-size/67421/4 "2021-08-31T12:50:57Z")

</div>

> [@Cevheriferd](#):
>
> But since I already know the data I am going to loop over I already know what the size of the dataframe will be.

What I mean is that it is better to populate the vectors first, and then create a data frame from them, e.g.:

```julia
julia> using DataFrames, BenchmarkTools

julia> 

julia> function test1()
           df = DataFrame(a=Vector{Int}(undef, 10^6),
                          b=Vector{String}(undef, 10^6),
                          c=Vector{Int}(undef, 10^6), copycols=false)
           for i in 1:10^6
               df.a[i] = 1
               df.b[i] = "1"
               df.c[i] = 1.0
           end
           return df
       end
test1 (generic function with 1 method)

julia> 

julia> function test2()
           nt = (a=Vector{Int}(undef, 10^6),
                 b=Vector{String}(undef, 10^6),
                 c=Vector{Int}(undef, 10^6))
           for i in 1:10^6
               nt.a[i] = 1
               nt.b[i] = "1"
               nt.c[i] = 1.0
           end
           return DataFrame(nt, copycols=false)
       end
test2 (generic function with 1 method)

julia> 

julia> @btime test1();
  244.934 ms (5998506 allocations: 160.20 MiB)

julia> @btime test2();
  4.881 ms (27 allocations: 22.89 MiB)

```

Since `DataFrame` object is not type stable it is best suited for operations that work on whole-columns, as then type instability is not an issue.

The benefit of not being type stable is that we can accommodate very wide data frames without huge compilation overhead + you can easily change the schema of a `DataFrame`.

---

_[View the full topic](https://discourse.julialang.org/t/how-to-initialize-empty-dataframe-of-specified-size/67421)._
