M.E.
M.E.

Reputation: 5515

Add a column of DateTime to an existing dataframe

I have the following DataFrame:

using DataFrames, Dates

df = DataFrame( A=Int[], B=Int[] )
push!(df, [1, 10])
push!(df, [2, 20])
push!(df, [3, 30])

df[!, :C] .= DateTime()

for r in eachrow(df)
    # Super complex function, simplified for example
    r.C = now() + Day(r.A)
end

But df[!, :C] .= DateTime() does not create a column with DateTime's (I want just to allocate the column, actual DateTimes will be populated via for i in eachrow loop).

Upvotes: 1

Views: 117

Answers (2)

Frames Catherine White
Frames Catherine White

Reputation: 28232

While @Daniel's answer is correct to question as asked.

You could replace your for loop with a map, and avoid having to preallocate.

df.C = map(eachrow(df) do r
    # Super complex function, simplified for example
    return now() + Day(r.A)
end

Upvotes: 2

Daniel Schwabeneder
Daniel Schwabeneder

Reputation: 226

There is no method DateTime(), try

df[!, :C] .= DateTime(0)

instead.

Upvotes: 2

Related Questions