How to define an empty array of DataFrames in Julia?

1.2k Views Asked by At

I want to generate an empty array of dataframes that will be filled later in the code, but I have not figured out how to do it. Any help would be appreciated!

I have tried a standard way of defining an empty array.

julia> df = Array{DataFrame}(undef,10)
10-element Array{DataFrame,1}:
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef
 #undef

julia> println(typeof(df[1]))
ERROR: UndefRefError: access to undefined reference
Stacktrace:
 [1] getindex(::Array{DataFrame,1}, ::Int64) at ./array.jl:729
 [2] top-level scope at none:0

I'd expected typeof(df[1]) to say DataFrame, but it fails with an error message.

2

There are 2 best solutions below

2
Bogumił Kamiński On BEST ANSWER

Try:

df_vector = [DataFrame() for _ in 1:10]

or

map(_ -> DataFrame(), 1:10)
4
Tasos Papastylianou On

What you have is correct, for your understood definition of 'empty'. Once you have your first result, you can proceed to fill it with dataframes as normal. It is indeed a DataFrame array, since if you try to assign any other type to its elements you will get an error.

Note that "an empty array of dataframes" is not the same as "a (non-empty) array of empty dataframes".

If what you actually want is the latter, Bogumil's answer is the way to go.