在我的例子中,我通过使用csv模块并像这样导入它来加载以下CSV数据(https://ourworldindata.org/coronavirus-source-data):
using DataFrames
using CSV
raw = CSV.read("data.csv")然后,我想通过索引来设置字符串列,如下所示:
raw[1, :location] = "AA"我得到了以下错误:
setindex! not defined for CSV.Column{String,PooledString}
Stacktrace:
[1] error(::String, ::Type) at ./error.jl:42
[2] error_if_canonical_setindex(::IndexLinear, ::CSV.Column{String,PooledString}, ::Int64) at ./abstractarray.jl:1006
[3] setindex!(::CSV.Column{String,PooledString}, ::String, ::Int64) at ./abstractarray.jl:997
[4] insert_single_entry!(::DataFrame, ::String, ::Int64, ::Symbol) at /home/chris/.julia/packages/DataFrames/S3ZFo/src/dataframe/dataframe.jl:452
[5] setindex!(::DataFrame, ::String, ::Int64, ::Symbol) at /home/chris/.julia/packages/DataFrames/S3ZFo/src/dataframe/dataframe.jl:491
[6] top-level scope at In[31]:1这是与我的类型有关,还是我完全做错了什么?举个简单的例子,它似乎是这样工作的:
df=DataFrames.DataFrame(A=[1,2],B=[3,4])
df[2,:A]=7发布于 2020-04-07 05:28:02
这是因为默认情况下,CSV.read返回的是一个不可变的数据帧,其底层存储是基于CSV.Column类型的。您可以使用copycols选项直接读取可变数据帧:
julia> using CSV
# Reading from a buffer for the sake of the example
julia> buf = IOBuffer("A B\n1 2\n3 4\n");
# Note the copycols=true keyword argument
julia> data = CSV.read(buf, copycols=true)
2×2 DataFrames.DataFrame
│ Row │ A │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 2 │
│ 2 │ 3 │ 4 │
# The dataframe is now mutable
julia> data[2, :A] = 42;
julia> data
2×2 DataFrames.DataFrame
│ Row │ A │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 2 │
│ 2 │ 42 │ 4 │另一种可能是在从CSV文件加载数据后将其转换为“常规”(即Array-based,可变) DataFrame。
例如:
julia> using DataFrames
# Reading from a buffer for the sake of the example
julia> buf = IOBuffer("A B\n1 2\n3 4\n");
# Pass the output of CSV.read to the DataFrame constructor
julia> data = CSV.read(buf) |> DataFrame
2×2 DataFrame
│ Row │ A │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 2 │
│ 2 │ 3 │ 4 │
# The dataframe is now mutable
julia> data[2, :A] = 42;
julia> data
2×2 DataFrame
│ Row │ A │ B │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 2 │
│ 2 │ 42 │ 4 │https://stackoverflow.com/questions/61068639
复制相似问题