What is “setindex! not defined” error in julia?

北城余情 提交于 2020-06-16 03:23:10

问题


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


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/61995125/what-is-setindex-not-defined-error-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!