What is "setindex! not defined" error in julia?

Viewed 792

When I run my code one error occurs with my code setindex! not defined for WeakRefStrings.StringArray{String,1}

CSV File here.

using CSV
EVDdata =CSV.read(raw"wikipediaEVDdatesconverted.csv")
EVDdata[end-9:end,:]

And the Error Code is here

rows, cols = size(EVDdata)
for j =1:cols
    for i = 1:rows
        if !isdigit(string(EVDdata[i, j])[1])
            EVDdata[i,j] = 0
        end
    end
end

I am working with Julia 1.4.1 on Jupter Notebook

3 Answers

setindex!(collection, item, inds...) is the function that colection[inds...] = item gets lowered to. The error comes from the fact that CSV.read makes an immutable collection.

As Oscar says in his answer, setindex! tries to mutate its arguments, i.e. change the contents of your column in place. When you do CSV.read(), by default immutable columns of type CSV.Column are returned. This is done for performance reason, as it means columns don't have to be copied after parsing.

To get around this, you can do two things:

  1. Pass the keyword argument CSV.read(raw"wikipediaEVDdatesconverted.csv", copycols = true) - this will copy the columns and therefore make them mutable; or
  2. Achieve the same by using DataFrame((raw"wikipediaEVDdatesconverted.csv"))

The second way is the preferred way as CSV.read will be deprecated in the CSV.jl package.

You can see that it's current implementation is basically doing the same thing I listed in (2) above in the source here. Removing this method will allow CSV.jl not to depend on DataFrames.jl anymore.

It could also be done this way

col1dt = Vector{Dates.DateTime}(undef, length(col1))

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

Related