codewithearth
codewithearth

Reputation: 75

setindex! error in julia? when using "For loop" for DateTime

I learn Julia from Coursera, And when I reached 2nd week lecture some codes error in my notebook. It give me setindex! not defined for WeakRefStrings.StringArray{String,1} error.

Csv File import here

using CSV, Dates
wikiEVDraw = CSV.read("wikipediaEVDraw1.csv")

Dates.DateTime.(wikiEVDraw[1,1],Ref("d-u-y"))

Date Code here

col1=wikiEVDraw[:,1] 

setindex! error here

for i = 1:length(col1)
    col1[i]=Dates.DateTime.(col1[i],Ref("d-u-y"))
end

Upvotes: 0

Views: 145

Answers (1)

This is because you forgot the dash (-) delimiter in your format string the second time.

Note that there is another error in your code: col1 is of type WeakRefStrings.StringArray which is (AFAIU) not really a data type that is intended to be manipulated. And in any case, it is intended to store strings, so you can not replace its elements with DateTime objects instead.

Instead, you can build (a copy of) the entire column, with each element converted to a DateTime object. Broadcasting syntax would probably the most idiomatic way to do this:

# Sample data
julia> col = ["01-Jan-2020", "02-Jan-2020", "03-Jan-2020"]
3-element Array{String,1}:
 "01-Jan-2020"
 "02-Jan-2020"
 "03-Jan-2020"

julia> using Dates

       # Note the '.' before the open parenthesis
julia> col = Dates.DateTime.(col, Ref("d-u-y"))
3-element Array{DateTime,1}:
 2020-01-01T00:00:00
 2020-01-02T00:00:00
 2020-01-03T00:00:00

Upvotes: 1

Related Questions