在DataFrames.jl表中更改数值的数据类型

huangapple go评论146阅读模式
英文:

Change data type of values in DataFrames.jl table

问题

需要更改DataFrame.jl对象中的值(或根据需要逐列更改数据类型)。特别是从String更改为Int。即使在最小示例中也没有遇到任何问题:

using DataFrames
df = DataFrame(x=["1", "2", "3"])
df.x[1] = parse(Int, df.x[1]) # 返回错误!

为什么?有什么解决方法?

英文:

I need to change the data type of a value (or column-wise if needed be) within a DataFrame.jl object. From String to Int specifically. Not encountering any luck even with the minimal example:

using DataFrames
df=DataFrame(x=["1","2","3"])
df.x[1]=parse(Int,df.x[1]) # Returns error!

Why? What's a workaround?

答案1

得分: 2

我认为问题在于数据框列仍然被设置为String类型,因此您无法将Int类型的值赋给它。您需要更改整个列的数据类型。类似下面的代码应该可以工作:

using DataFrames
df = DataFrame(x=["1", "2", "3"])
select(df, :x => ByRow(x -> parse(Int, x)) => :x)
英文:

I think the problem is that the data frame column is still set to be of type String so that you cannot assign a value of type Int to it. You would have to change the type of the whole column. Something like below should work:

using DataFrames
df=DataFrame(x=["1","2","3"])
select(df, :x => ByRow(x -> parse(Int, x)) => :x)

答案2

得分: 1

更好的选项(更快,减少内存分配)只需:

using DataFrames
df = DataFrame(x=["1", "2", "3"])
df.x .= parse.(Int, df.x)
英文:

A better option (faster, less allocations) would be just:

using DataFrames
df=DataFrame(x=["1","2","3"])
df.x .= parse.(Int, df.x)

huangapple
  • 本文由 发表于 2023年3月4日 00:01:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定