psych0groov3
psych0groov3

Reputation: 701

Transform multiple columns from strings to dates

I want to define a function that takes a dataframe (df::DataFrame) and the names of the columns to transform to dates (cols::Vector{Symbol})

What I have is this:

function fixDateColumns(df::DataFrame, cols::Vector{Symbol})
    function stringsToDates(dates::Vector)
        Date.(dates, dateformat"yyyy-mm-dd HH:MM:SS")
    end
    dates = stringsToDates(df[!, cols])
    df[!, cols] = dates
    return df
end

When calling this function like this:

fixDateColumns(df, [:Start_Date, :End_Date, :Recorded_Date])

I'm getting the following error:

ERROR: MethodError: no method matching (::var"#stringsToDates#11")(::DataFrame)
Closest candidates are:
  (::var"#stringsToDates#11")(::Vector

Any idea what I'm doing wrong?

Upvotes: 1

Views: 109

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69819

Do:

transform!(df, cols .=> ByRow(x -> Date(x, dateformat"yyyy-mm-dd HH:MM:SS")) .=> cols)

or

df[!, cols] = Date.(df[!, cols], dateformat"yyyy-mm-dd HH:MM:SS")

Upvotes: 1

Related Questions