Writing values to an empty dataframe column in Julia

Viewed 425

There is a dataframe with some values. I need to add an empty column to it, so that I can then fill in its individual cells with values when information on them becomes available. The type of values is known in advance, for example, let it be Float64, but if during initialization I set the contents of the column as "missing", then the type of the column is also displayed as "Missing" and no numeric values can be written there later. Here is an example illustrating the problem:

df = DataFrame(a = 1:3, b = 1.0:3.0)
insertcols!(df, 3, :c => missing)
df.b[1] = 5.0 # it works
df.c[1] = 7.0 # give an error

What is the right thing to do in this situation? Is needed to change the way of empty column initialization or the way of recording in its cells?

1 Answers

One possible way you could try:

insertcols!(df,  :c => Vector{Union{Float64,Missing}}(missing,nrow(df)))

or:

df[!,:c] = Vector{Union{Float64,Missing}}(missing,nrow(df))

or shorter as mentioned by @Milan Bouchet-Valat:

df[!,:c] = missings(Float64, nrow(df))
Related