Set index! not defined for WeakRefStrings. SpringArray{String,1}

Viewed 82

i wanted to create a loop on a column in my IJulia and I came up with this error. Please what can I do to rectify it.

Here is my code:

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

And I got this error:

setindex! not defined for WeakRefStrings.StringArray{String,1}

Stacktrace:
 [1] error(::String, ::Type{T} where T) at .\error.jl:42
 [2] error_if_canonical_setindex(::IndexLinear, ::WeakRefStrings.StringArray{String,1}, ::Int64) at .\abstractarray.jl:1081
 [3] setindex!(::WeakRefStrings.StringArray{String,1}, ::DateTime, ::Int64) at .\abstractarray.jl:1072
 [4] top-level scope at .\In[130]:2

I decided to try changing the code a little bit using:

for i in col1
       global col1[i] = Dates.DateTime(string.(col1[i]), "d-u-y")
end

Then I still got this error:

ArgumentError: invalid index: "4-Jul-2014" of type String

Stacktrace:
 [1] to_index(::String) at .\indices.jl:297
 [2] to_index(::WeakRefStrings.StringArray{String,1}, ::String) at .\indices.jl:274
 [3] to_indices at .\indices.jl:325 [inlined]
 [4] to_indices at .\indices.jl:322 [inlined]
 [5] getindex(::WeakRefStrings.StringArray{String,1}, ::String) at .\abstractarray.jl:980
 [6] top-level scope at .\In[136]:2
1 Answers

There are two separate issues at play here. The first issue as that you likely read in some data using CSV.read(), which gives you an immutable set of columns. As they are immutable, setindex! (essentially changing the contents) is not allowed. A question on this has been answered here.

The second issue is unrelated and is due to the fact that you are now iterating over the actual column col1, so that i is not an integer anymore, but takes the value of whatever is in col1, in your case a WeakRefString. So when you do col1[i], i has the value "4-Jul-2014", because that's the first value in the col1 column.

In any case you don't need to loop here at all, but can simply rely on Julia's broadcasting syntax like so:

Date.(col1, DateFormat("d-u-y"))

The dot after Date broadcasts the Date constructor over each element of col1. Note also that you can just use Date rather than DateTime as based on the date that shows up in your error messages it looks like your data doesn't have a time attached to it.

Related