英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论