首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置数据框对象的值

设置数据框对象的值
EN

Stack Overflow用户
提问于 2020-04-07 04:42:42
回答 1查看 159关注 0票数 4

在我的例子中,我通过使用csv模块并像这样导入它来加载以下CSV数据(https://ourworldindata.org/coronavirus-source-data):

代码语言:javascript
复制
using DataFrames
using CSV

raw = CSV.read("data.csv")

然后,我想通过索引来设置字符串列,如下所示:

代码语言:javascript
复制
raw[1, :location] = "AA"

我得到了以下错误:

代码语言:javascript
复制
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

这是与我的类型有关,还是我完全做错了什么?举个简单的例子,它似乎是这样工作的:

代码语言:javascript
复制
df=DataFrames.DataFrame(A=[1,2],B=[3,4])

df[2,:A]=7
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-07 05:28:02

这是因为默认情况下,CSV.read返回的是一个不可变的数据帧,其底层存储是基于CSV.Column类型的。您可以使用copycols选项直接读取可变数据帧:

代码语言:javascript
复制
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

例如:

代码语言:javascript
复制
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     │
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61068639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档