我有一个 DataFrame,它有许多 String 列,它们应该是 float64。我想一次转换所有列并将数据帧转换为浮点数组。怎么能做到这一点?重要的是,还有一些 float 列。
df = DataFrame(a=["1", "2", "3"], b=["1.1", "2.2", "3.3"], c=[0.1, 0.2, 0.3])
# Verbose option
df.a = parse.(Float64, df.a)
df.b = parse.(Float64, df.b)
matrix = Matrix{Float64}(df)
# Is is possible to do this at once especially when there are float columns too?
# Here parse.(Float64, df.c) would throw an error
最佳答案
一种方法是循环遍历字符串列:
for c ∈ names(df, String)
df[!, c]= parse.(Float64, df[!, c])
end
请注意,您不需要 Matrix{Float64}
如果你已经把所有东西都变成了 Floats,只需 Matrix(df)
会做。
关于dataframe - Julia:将具有多个字符串列的 Dataframe 转换为 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69541829/